美文网首页
JAVA面试锦集01-如何保证线程的顺序

JAVA面试锦集01-如何保证线程的顺序

作者: Steven_cao | 来源:发表于2018-08-01 23:18 被阅读41次

1、Thread.join() 方法

    调用Object.wait()方法,他的目的是暂停主线程,等待执行完子线程后主线程才继续执行。

2、Executors.newSingleThreadExecutor() 一个线程的线程池

    加入到调度队列中 由于队列是FIFO所以可以按加入顺序执行。

```

public class Interview01 {

static Thread thread1 =new Thread(() -> System.out.println("thread1"));

static Thread thread2 =new Thread(() -> System.out.println("thread2"));

static Thread thread3 =new Thread(() -> System.out.println("thread3"));

    public static void main(String[] args) {

        //1 Thread.join()

//        method1();

        //2 Executors.newSingleThreadExecutor()

        method2();

    }

    public static void  method1(){

        thread1.start();

        try {

            thread1.join();

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

        thread2.start();

        try {

            thread2.join();

        } catch (InterruptedException e) {

            e.printStackTrace();

        }

        thread3.start();

    }

    public static void method2(){

        ExecutorService executorService = Executors.newSingleThreadExecutor();

        executorService.submit(thread1);

        executorService.submit(thread2);

        executorService.submit(thread3);

        executorService.shutdown();

    }

}

```

相关文章

网友评论

      本文标题:JAVA面试锦集01-如何保证线程的顺序

      本文链接:https://www.haomeiwen.com/subject/leudvftx.html