保证十个线程的执行顺序、保证主线程等待子线程执行完毕再执行

1、通过thread的join方法保证多线程的顺序执行, wait是让主线程等待

比如一个main方法里面先后运行thread1,,thread2,thread3,那么thread1.start()之后,运行thread1.join(),这是会让主线程mian等待新的线程thread1执行完了,再执行主线程mian下面的代码,thread1.join()是然主线程main wait。

public class MultiThread {
    public static void main(String[] args) throws InterruptedException {
        Thread thread1 = new Thread(new Thread1());
        thread1.start();
        thread1.join();
        Thread thread2 = new Thread(new Thread2());
        thread2.start();
        thread2.join();
        Thread thread3 = new Thread(new Thread3());
        thread3.start();
    }
    }

2 、ExecutorService executor = Executors.newSingleThreadExecutor()

java5以后提供的一个多线程操作方法,创建一个只有一个线程的线程池操作,会创建一个线程队列,按FIFO的顺序执行里面的线程。

public class MultiThread2 {
    public static void main(String[] args) throws InterruptedException {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        executor.submit(new Thread1());
        executor.submit(new Thread2());
        executor.submit(new Thread3());
        executor.shutdown();
    }
}

3、 Lock和synchronized

ReadWriteLock
ReadLock
WriteLock
ReenterantLock可重入锁
可中断锁
公平锁 等待一个锁的实际越长,获取这个锁的几率越高
ReenterantReadWriteLock 可重入读写锁
Lock是java里面的一个接口,有丰富的实现,而synchronized是java的一个关键字,是一个内置的功能


主线程等待子线程执行完毕再执行的四种方法

①、t1.join()
②、while(t1.isAlive())
③、while(Thread.activeCount()>1)
④、CountDownLatch

public class WaitThreadDone {
    public static void main(String[] args) throws InterruptedException {
        final CountDownLatch latch = new CountDownLatch(1);   //④
        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("thread " + Thread.currentThread().getName() + " start to  run");
                    Thread.sleep(2000);
                    System.out.println("thread " + Thread.currentThread().getName() + " done");
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    latch.countDown();
                }
            }
        });
        System.out.println("main start to run.");
        t1.start();
//      t1.join();      ①
//        while(t1.isAlive()){   ②
//
//        }
//        while (Thread.activeCount() > 1){   ③
//            Thread.yield();
//        }
        latch.await();
        System.out.println("main done");
    }
}

你可能感兴趣的:(保证十个线程的执行顺序、保证主线程等待子线程执行完毕再执行)