码迷,mamicode.com
首页 > 编程语言 > 详细

线程池(6)简单创建线程3种实现

时间:2019-02-01 11:36:36      阅读:157      评论:0      收藏:0      [点我收藏+]

标签:.com   分享   style   ring   for   star   import   .exe   exce   

3种实现:thread、runnable、callable

技术分享图片

1、thread

@Slf4j
public class MyThread extends Thread {
    @Override
    public void run() {
        log.info("线程ID:{}",Thread.currentThread().getId());
    }
    
}

public class MyTest {
    public static void main(String[] args) {
        MyThread thread = new MyThread();
        thread.start();
    }
}
输出:10:09:08.152 [Thread-0] INFO  c.e.thread.MyThread:9 - 线程ID:10

2、runnable

@Slf4j
public class MyRunnable implements Runnable {
    public MyRunnable() {
    }
    @Override
    public void run() {
        log.info("线程ID:{}",Thread.currentThread().getId());
    }
}

public class MyTest {
    public static void main(String[] args) {
        MyRunnable r = new MyRunnable();
        new Thread(r).start();
    }
}
输出:10:09:20.272 [Thread-0] INFO  c.e.r.MyRunnable:10 - 线程ID:10

 

3、callable

import java.util.concurrent.Callable;

public class MyCallable implements Callable<Integer> {
    @Override
    public Integer call() throws Exception {
        int sum = 0;
        for (int i = 0; i < 10000*100; i++) {
            sum = sum +1;
        }
        return sum;
    }
}

import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

import lombok.extern.slf4j.Slf4j;
@Slf4j
public class MyTest {
    public static void main(String[] args) {
        MyCallable c = new MyCallable();
        FutureTask<Integer> result = new FutureTask<>(c);
        new Thread(result).start();
        try {
            Integer sum = result.get();
            log.info("{}",sum);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
    }
}
输出:10:08:49.349 [main] INFO  c.e.callable.MyTest:15 - 1000000

 

线程池(6)简单创建线程3种实现

标签:.com   分享   style   ring   for   star   import   .exe   exce   

原文地址:https://www.cnblogs.com/yaoyuan2/p/10344900.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!