zoukankan      html  css  js  c++  java
  • 线程池(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
  • 相关阅读:
    C#网络编程之---TCP协议的同步通信(二)
    CentOS6.4 X86_64 kvm+PXE备忘
    Rsyslog远程传输的几种方式
    ADB工具【转载】
    docker 常用命令
    容灾测试(未完)
    docker 运维实践
    Day 15 图像和办公文档的处理
    服务器调优
    软件测试1 正规流程
  • 原文地址:https://www.cnblogs.com/yaoyuan2/p/10344900.html
Copyright © 2011-2022 走看看