Java代码中如何让线程按顺序运行呢?

乔欣 Java经验 发布时间:2022-12-11 17:20:35 阅读数:11888 1
由于某些特殊的原因,我们必须让线程按照一定的顺序运行,那么如何实现这个需求呢?
下文笔者将一一道来,如下所示
下文笔者列举了八种让线程顺序运行的方法
实现思路:
    使用线程join方法
	使用主线程join方法
	使用线程wait方法
	使用线程线程池方法
	使用线程Condition(条件变量)方法
	使用线程CountDownLatch(倒计数)方法
	使用线程CyclicBarrier(回环栅栏)方法
	使用线程Semaphore(信号量)方法   

例1:使用线程的join方法

join():
   是Theard中方法
   其功能是调用线程需等待该join()线程执行完成后
    才能继续用下运行 

join方法应用场景:
    当一个线程必须等待另一个线程运行完毕
	 才能运行时
	此时可使用join方法
例:
package com.java265.thread;
public class ThreadJoinMain {
    public static void main(String[] args) {
        final Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程1运行!");
            }
        });
 
        final Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    thread1.join();
                    System.out.println("线程2运行!");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
 
        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    thread2.join();
                    System.out.println("线程3运行");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
 
        System.out.println("1");
        System.out.println("1要开始运行...");
        thread3.start();
        System.out.println("2要开始运行...");
        thread1.start();
        System.out.println("3要开始运行了...");
        thread2.start();
    }
}

方式2:使用主线程的join方法

 此方法的原理:
      在主线程中使用join()
      实现对线程阻塞
package com.java265.thread;
 
public class MainThreadJoinMain {
    public static void main(String[] args) throws InterruptedException {
        final Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程1运行...");
            }
        });
 
        final Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程2运行");
            }
        });
 
        final Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程3运行");
            }
        });
 
        System.out.println("开始:");
        System.out.println("1运行");
        System.out.println("2运行");
        System.out.println("3运行");
        thread1.start();
        //在父进程调用子进程的join()方法后,父进程需要等待子进程运行完再继续运行。 
        thread1.join(); 
        thread2.start(); 
        thread2.join();
        thread3.start();
    }
}

方式3:运行线程的wait方法

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

notify()和notifyAll(): 
     是Object中方法
    其功能唤醒当前对象上的等待线程;
	  notify()是唤醒单个线程
      notifyAll()是唤醒所有的线程

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

使用场景
     Java实现生产者消费者的方式
例:
package com.java265.thread;
 
public class ThreadWaitMain {
    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("线程1规划新需求...");
                    t1Run = true;
                    myLock1.notify();
                }
            }
        });
 
        final Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (myLock1) {
                    try {
                        if (!t1Run) {
                            System.out.println("线程2先休息会...");
                            myLock1.wait();
                        }
                        synchronized (myLock2) {
                            System.out.println("线程2开发新需求功能");
                            myLock2.notify();
                        }
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
 
        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                synchronized (myLock2) {
                    try {
                        if (!t2Run) {
                            System.out.println("线程3先休息会...");
                            myLock2.wait();
                        }
                        System.out.println("线程3测试新功能");
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
 
        System.out.println("早上:");
        System.out.println("线程3准备运行...");
        thread3.start();
        System.out.println("线程1准备运行...");
        thread1.start();
        System.out.println("线程2准备运行...");
        thread2.start();
    }
}

方式4:使用线程的线程池方法

我们都知道Java中线程池可使用四种线程池
   单线程化线程池(newSingleThreadExecutor);
  可控最大并发数线程池(newFixedThreadPool);
  可回收缓存线程池(newCachedThreadPool);
  支持定时与周期性任务的线程池(newScheduledThreadPool)。
  
  单线程化线程池(newSingleThreadExecutor):优点
      串行执行所有任务。
其中拥有
submit()
    提交任务
shutdown()
    方法用来关闭线程池,拒绝新任务。
下文笔者就采用newSingleThreadExecutor实现线程顺序运行
package com.java265.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolMain {
    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("线程1规划新需求");
            }
        });
 
        final Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程2开发新需求功能");
            }
        });
 
        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程3测试新功能");
            }
        });
 
        System.out.println("早上:");
        System.out.println("线程1准备运行");
        System.out.println("线程3准备运行");
        System.out.println("线程2准备运行");
        System.out.println("============");
        System.out.println("首先,线程1规划新需求...");
        executorService.submit(thread1);
        System.out.println("然后,线程2开发新需求功能...");
        executorService.submit(thread2);
        System.out.println("最后,线程3测试新功能...");
        executorService.submit(thread3);
        executorService.shutdown();
    }
}

方式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实现线程的顺序运行
package com.java265.thread;
 
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
 
public class ThreadConditionMain {
    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("线程1规划新需求");
                t1Run = true;
                condition1.signal();
                lock.unlock();
            }
        });
 
        final Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                try {
                    if (!t1Run) {
                        System.out.println("线程2先休息会...");
                        condition1.await();
                    }
                    System.out.println("线程2开发新需求功能");
                    t2Run = true;
                    condition2.signal();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                lock.unlock();
            }
        });
 
        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                lock.lock();
                try {
                    if (!t2Run) {
                        System.out.println("线程3先休息会...");
                        condition2.await();
                    }
                    System.out.println("线程3测试新功能");
                    lock.unlock();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
 
        System.out.println("早上:");
        System.out.println("线程3准备运行...");
        thread3.start();
        System.out.println("线程1准备运行...");
        thread1.start();
        System.out.println("线程2准备运行...");
        thread2.start();
    }
}

方式6:使用线程的CountDownLatch(倒计数)方法

CountDownLatch:
    实现类似计数器的功能
package com.java265.thread;
 
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
 
public class ThreadCountDownLatchMain {
    /**
     * 用于判断线程一是否执行,倒计时设置为1,执行后减1
     */
    private static CountDownLatch c1 = new CountDownLatch(1);
 
    /**
     * 用于判断线程二是否执行,倒计时设置为1,执行后减1
     */
    private static 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("线程1规划新需求");
                //对c1倒计时-1
                c1.countDown();
            }
        });
 
        final Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //等待c1倒计时,计时为0则往下运行
                    c1.await();
                    System.out.println("线程2开发新需求功能");
                    //对c2倒计时-1
                    c2.countDown();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
 
        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //等待c2倒计时,计时为0则往下运行
                    c2.await();
                    System.out.println("线程3测试新功能");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
 
        System.out.println("早上:");
        System.out.println("线程3准备运行...");
        thread3.start();
        System.out.println("线程1准备运行...");
        thread1.start();
        System.out.println("线程2准备运行...");
        thread2.start();
    }
}

方式7:
使用CyclicBarrier(回环栅栏)实现线程按顺序运行

 CyclicBarrier(回环栅栏):
    使用它可以实现让一组线程等待至某个状态之后再全部同时执行
 
package com.java265.thread;
 
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
 
public class CyclicBarrierMain {
    static CyclicBarrier barrier1 = new CyclicBarrier(2);
    static CyclicBarrier barrier2 = new CyclicBarrier(2);
 
    public static void main(String[] args) {
 
        final Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.println("线程1规划新需求");
                    //放开栅栏1
                    barrier1.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        });
 
        final Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //放开栅栏1
                    barrier1.await();
                    System.out.println("线程2开发新需求功能");
                    //放开栅栏2
                    barrier2.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        });
 
        final Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //放开栅栏2
                    barrier2.await();
                    System.out.println("线程3测试新功能");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                } catch (BrokenBarrierException e) {
                    e.printStackTrace();
                }
            }
        });
 
        System.out.println("早上:");
        System.out.println("线程3准备运行...");
        thread3.start();
        System.out.println("线程1准备运行...");
        thread1.start();
        System.out.println("线程2准备运行...");
        thread2.start();
    }
}

方式8:使用Sephmore(信号量)实现线程按顺序运行

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

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

release():
    当前线程释放1个可用的许可证
 
package com.java265.thread;
import java.util.concurrent.Semaphore;
public class SemaphoreMain {
    private static Semaphore semaphore1 = new Semaphore(1);
    private static Semaphore semaphore2 = new Semaphore(1);
 
    public static void main(String[] args) {
        final Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("线程1规划新需求");
                semaphore1.release();
            }
        });
 
        final Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    semaphore1.acquire();
                    System.out.println("线程2开发新需求功能");
                    semaphore2.release();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
 
        Thread thread3 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    semaphore2.acquire();
                    thread2.join();
                    semaphore2.release();
                    System.out.println("线程3测试新功能");
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        });
 
        System.out.println("早上:");
        System.out.println("线程3准备运行...");
        thread3.start();
        System.out.println("线程1准备运行...");
        thread1.start();
        System.out.println("线程2准备运行...");
        thread2.start();
    }
}
版权声明

本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。

本文链接: https://www.Java265.com/JavaJingYan/202212/16707505275115.html

最近发表

热门文章

好文推荐

Java265.com

https://www.java265.com

站长统计|粤ICP备14097017号-3

Powered By Java265.com信息维护小组

使用手机扫描二维码

关注我们看更多资讯

java爱好者