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


    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
  • 相关阅读:
    【转】GitHub 中国区前 100 名到底是什么样的人?
    不同服务器数据库之间的数据操作
    行列互换
    千万级数据查询
    用命令对sql进行备份
    通过SQL Server 2008数据库复制实现数据库同步备份
    各种字符串合并处理示例.
    字符串分解
    四大排序函数
    cross apply 和 outer apply
  • 原文地址:https://www.cnblogs.com/yaoyuan2/p/10344900.html
Copyright © 2020-2023  润新知