多线程-顺序执行

1.多线程如何保证顺序执行

[0] CompletableFuture
[1] 使用线程的join方法
[2] 使用主线程的join方法
[3] 使用线程的wait方法
[4] 使用线程的线程池方法
[5] 使用线程的Condition(条件变量)方法
[6] 使用线程的CountDownLatch(倒计数)方法
[7] 使用线程的CyclicBarrier(回环栅栏)方法
[8] 使用线程的Semaphore(信号量)方法

1.1用CompletableFuture

只能保证线程执行顺序,不保证输出结果是顺序的

public class ThreadSortTest {

    public static void main(String[] args) {

        Thread t1 = new Thread(()->{
            System.out.println(Thread.currentThread().getName() + "执行");
        },"t1");

        Thread t2 = new Thread(()->{
            System.out.println(Thread.currentThread().getName() + "执行");
        },"t2");

        Thread t3 = new Thread(()->{
            System.out.println(Thread.currentThread().getName() + "执行");
        },"t3");

        CompletableFuture.runAsync(t1::start)
                .thenRun(t2::start)
                .thenRun(t3::start);
    }

}

Java8 CompletableFuture 用法全解

1.2用join

public static void join() {
        Thread t1 = new Thread(()->{
            System.out.println(Thread.currentThread().getName() + "执行");
        },"t1");

        Thread t2 = new Thread(()->{
            try {
                t1.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "执行");
        },"t2");

        Thread t3 = new Thread(()->{
            try {
                t2.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println(Thread.currentThread().getName() + "执行");
        },"t3");

        t1.start();
        t2.start();
        t3.start();
        System.out.println("=====================");
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        t1.interrupt();
        if(t1.isInterrupted()) {
            return;
        }
        t2.interrupt();
        if(t2.isInterrupted()) {
            return;
        }
        t3.interrupt();
        if(t3.isInterrupted()) {
            return;
        }

    }
   

1.3使用线程的wait方法

wait():是Object的方法,作用是让当前线程进入等待状态,同时,wait()也会让当前线程释放它所持有的锁。“直到其他线程调用此对象的 notify() 方法或 notifyAll() 方法”,当前线程被唤醒(进入“就绪状态”)

notify()和notifyAll():是Object的方法,作用则是唤醒当前对象上的等待线程;notify()是唤醒单个线程,而notifyAll()是唤醒所有的线程。

wait(long timeout):让当前线程处于“等待(阻塞)状态”,“直到其他线程调用此对象的notify()方法或 notifyAll() 方法,或者超过指定的时间量”,当前线程被唤醒(进入“就绪状态”)。

应用场景:Java实现生产者消费者的方式。

public class ThreadSortWait {

    private static Object myLock1 = new Object();
    private static Object myLock2 = new Object();

    /**
     * 为什么要加这两个标识状态?
     * 如果没有状态标识,当t1已经运行完了t2才运行,t2在等待t1唤醒导致t2永远处于等待状态
     */
    private static Boolean t1Run = false;
    private static Boolean t2Run = false;
    public static void main(String[] args) {

        final Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (myLock1){
                    System.out.println(Thread.currentThread().getName() + "执行");
                    t1Run = true;
                    myLock1.notify();
                }
            }
        },"t1");

        final Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (myLock1){
                    try {
                        if(!t1Run){
                            System.out.println("t2先休息会...");
                            myLock1.wait();
                        }
                        synchronized (myLock2){
                            System.out.println(Thread.currentThread().getName() + "执行");
                            t2Run = true;
                            myLock2.notify();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        },"t2");

        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (myLock2){
                    try {
                        if(!t2Run){
                            System.out.println("t3先休息会...");
                            myLock2.wait();
                        }
                        System.out.println(Thread.currentThread().getName() + "执行");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        },"t3");

        thread2.start();
        thread1.start();
        thread3.start();
    }
}

运行结果

t2先休息会...
t3先休息会...
t1执行
t2执行
t3执行

1.4使用线程的线程池方法

JAVA通过Executors提供了四种线程池

  • 单线程化线程池(newSingleThreadExecutor);
  • 可控最大并发数线程池(newFixedThreadPool);
  • 可回收缓存线程池(newCachedThreadPool);
  • 支持定时与周期性任务的线程池(newScheduledThreadPool)。

单线程化线程池(newSingleThreadExecutor):优点,串行执行所有任务

  • submit():提交任务。
  • shutdown():方法用来关闭线程池,拒绝新任务。

应用场景:串行执行所有任务。如果这个唯一的线程因为异常结束,那么会有一个新的线程来替代它。此线程池保证所有任务的执行顺序按照任务的提交顺序执行。

public class ThreadSortPool {

    static ExecutorService executorService = Executors.newSingleThreadExecutor();

    public static void main(String[] args) throws Exception {

        final Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "执行1");
            }
        },"t1");

        final Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "执行2");
            }
        },"t2");

        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "执行3");
            }
        },"t3");

        executorService.submit(thread1);
        executorService.submit(thread2);
        executorService.submit(thread3);
        executorService.shutdown();
    }
}

运行结果:

pool-1-thread-1执行1
pool-1-thread-1执行2
pool-1-thread-1执行3

1.5使用线程的Condition(条件变量)方法

Condition(条件变量):通常与一个锁关联。需要在多个Contidion中共享一个锁时,可以传递一个Lock/RLock实例给构造方法,否则它将自己生成一个RLock实例。

  • Condition中await()方法类似于Object类中的wait()方法。
  • Condition中await(long time,TimeUnit unit)方法类似于Object类中的wait(long time)方法。
  • Condition中signal()方法类似于Object类中的notify()方法。
  • Condition中signalAll()方法类似于Object类中的notifyAll()方法。

应用场景:Condition是一个多线程间协调通信的工具类,使得某个,或者某些线程一起等待某个条件(Condition),只有当该条件具备( signal 或者 signalAll方法被带调用)时 ,这些等待线程才会被唤醒,从而重新争夺锁。

public class ThreadSortCondition {

    private static Lock lock = new ReentrantLock();
    private static Condition condition1 = lock.newCondition();
    private static Condition condition2 = lock.newCondition();

    /**
     * 为什么要加这两个标识状态?
     * 如果没有状态标识,当t1已经运行完了t2才运行,t2在等待t1唤醒导致t2永远处于等待状态
     */
    private static Boolean t1Run = false;
    private static Boolean t2Run = false;

    public static void main(String[] args) {

        final Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                System.out.println(Thread.currentThread().getName() + "执行");
                t1Run = true;
                condition1.signal();
                lock.unlock();
            }
        }, "t1");

        final Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();

                try {
                    if (!t1Run) {
                        System.out.println("t2先休息会...");
                        condition1.await();
                    }
                    System.out.println(Thread.currentThread().getName() + "执行");
                    t2Run = true;
                    condition2.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                lock.unlock();
            }
        }, "t2");

        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                try {
                    if (!t2Run) {
                        System.out.println("t3先休息会...");
                        condition2.await();
                    }
                    System.out.println(Thread.currentThread().getName() + "执行");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                lock.unlock();
            }
        }, "t3");

        thread2.start();
        thread1.start();
        thread3.start();
    }

}

运行结果:

t2先休息会...
t3先休息会...
t1执行
t2执行
t3执行

1.6使用线程的CountDownLatch(倒计数)方法

CountDownLatch:位于java.util.concurrent包下,利用它可以实现类似计数器的功能

应用场景:比如有一个任务C,它要等待其他任务A,B执行完毕之后才能执行,此时就可以利用CountDownLatch来实现这种功能了。

public class ThreadSortCountDownLatch {

    /**
     * 用于判断线程一是否执行,倒计时设置为1,执行后减1
     */
    private static final CountDownLatch c1 = new CountDownLatch(1);

    /**
     * 用于判断线程二是否执行,倒计时设置为1,执行后减1
     */
    private static final CountDownLatch c2 = new CountDownLatch(1);

    public static void main(String[] args) {
        final Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "执行");
                //对c1倒计时-1
                c1.countDown();
            }
        },"t1");

        final Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //等待c1倒计时,计时为0则往下运行
                    c1.await();
                    System.out.println(Thread.currentThread().getName() + "执行");
                    //对c2倒计时-1
                    c2.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"t2");

        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //等待c2倒计时,计时为0则往下运行
                    c2.await();
                    System.out.println(Thread.currentThread().getName() + "执行");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        },"t3");

        thread3.start();
        thread1.start();
        thread2.start();
    }
}

1.7使用Sephmore(信号量)实现线程按顺序运行

Sephmore(信号量):Semaphore是一个计数信号量,从概念上将,Semaphore包含一组许可证,如果有需要的话,每个acquire()方法都会阻塞,直到获取一个可用的许可证,每个release()方法都会释放持有许可证的线程,并且归还Semaphore一个可用的许可证。然而,实际上并没有真实的许可证对象供线程使用,Semaphore只是对可用的数量进行管理维护。

acquire():当前线程尝试去阻塞的获取1个许可证,此过程是阻塞的,当前线程获取了1个可用的许可证,则会停止等待,继续执行。

release():当前线程释放1个可用的许可证。

应用场景:Semaphore可以用来做流量分流,特别是对公共资源有限的场景,比如数据库连接。假设有这个的需求,读取几万个文件的数据到数据库中,由于文件读取是IO密集型任务,可以启动几十个线程并发读取,但是数据库连接数只有10个,这时就必须控制最多只有10个线程能够拿到数据库连接进行操作。这个时候,就可以使用Semaphore做流量控制。

public class ThreadSortCountSemaphore {

    /**
     * 用于判断线程一是否执行
     */
    private static final Semaphore semaphore1 = new Semaphore(0);

    /**
     * 用于判断线程二是否执行
     */
    private static final Semaphore semaphore2 = new Semaphore(0);

    public static void main(String[] args) {
        final Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println(Thread.currentThread().getName() + "执行");
                semaphore1.release();
            }
        }, "t1");

        final Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    semaphore1.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "执行");
                semaphore2.release();

            }
        }, "t2");

        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    semaphore2.acquire();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + "执行");
            }
        }, "t3");

        thread3.start();
        thread1.start();
        thread2.start();
    }
}

执行结果:

t1执行
t2执行
t3执行

1.8使用CyclicBarrier(回环栅栏)实现线程按顺序运行

CyclicBarrier(回环栅栏):通过它可以实现让一组线程等待至某个状态之后再全部同时执行。叫做回环是因为当所有等待线程都被释放以后,CyclicBarrier可以被重用。我们暂且把这个状态就叫做barrier,当调用await()方法之后,线程就处于barrier了。

应用场景:公司组织春游,等待所有的员工到达集合地点才能出发,每个人到达后进入barrier状态。都到达后,唤起大家一起出发去旅行。

public class ThreadSortCyclicBarrier {

    private static final CyclicBarrier cyclicBarrier1 = new CyclicBarrier(2);
    private static final CyclicBarrier cyclicBarrier2 = new CyclicBarrier(2);

    public static void main(String[] args) {
        final Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println(Thread.currentThread().getName() + "执行");
                    cyclicBarrier1.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        }, "t1");

        final Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    cyclicBarrier1.await();
                    System.out.println(Thread.currentThread().getName() + "执行");
                    cyclicBarrier2.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        }, "t2");

        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {

                try {
                    cyclicBarrier2.await();
                    System.out.println(Thread.currentThread().getName() + "执行");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        }, "t3");

        thread3.start();
        thread1.start();
        thread2.start();
    }
}

执行结果:

t1执行
t2执行
t3执行
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值