并发编程

线程基础-01

2019-08-16  本文已影响0人  愤怒的奶牛
  1. 创建线程的三种方式:
static class MyThread extends Thread {
   @Override
        public void run() {
             System.out.println("继承 Thread 创建线程");
        }
}
  static class MyThreadImpl implements Runnable {
        @Override
        public void run() {
            System.out.println("实现 Runnable 接口");
        }
    }
static class MyCallable implements Callable{
        @Override
        public Object call() throws Exception {
            return null;
        }
    }
  1. 线程启动
 public static void main(String[] args) throws ExecutionException, InterruptedException {
        //第一种启动
        new MyThread().start();
        // 第二种启动
        new Thread(new MyThreadImpl()).start();
        
        // 第三种启动,Executors 创建单个线程
        ExecutorService executorService = Executors.newSingleThreadExecutor();
        Future submit = executorService.submit(new MyCallable());
        Object result = submit.get(); //阻塞当前线程(Main),等待MyCallable 线程返回结果。
    }
上一篇 下一篇

猜你喜欢

热点阅读