300字范文,内容丰富有趣,生活中的好帮手!
300字范文 > java线程按顺序执行交替执行

java线程按顺序执行交替执行

时间:2022-12-31 16:25:40

相关推荐

java线程按顺序执行交替执行

java线程按顺序执行/交替执行

1.顺序执行多个线程

public class Test25 {static final Object lock = new Object();// 表示 t2 是否运行过static boolean t2runned = false;public static void main(String[] args) {Thread t1 = new Thread(() -> {synchronized (lock) {while (!t2runned) {try {lock.wait();//前面的线程还没有执行,进入阻塞等待} catch (InterruptedException e) {e.printStackTrace();}}log.debug("1");}}, "t1");Thread t2 = new Thread(() -> {synchronized (lock) {log.debug("2");t2runned = true;lock.notify(); //唤醒阻塞线程继续往下执行}}, "t2");t1.start();t2.start();}}//使用park和unpark进行实现public class TestPark{public static void main(String[] args){Thread t1 = new Thread(()->{LockSupport.park();log.debug("1");},"t1");t1.start();new Thread(()->{log.debug("2");LockSupport.unpark(t1);},"t2").start();}}

2.交替执行多个线程

​ 首先基本思想是封装好一个类用来接收信息,设计好参数由参数来控制当前谁执行,下一个谁执行,然后在主线程设定好交替顺序。

public class Test27 {public static void main(String[] args) {WaitNotify wn = new WaitNotify(1, 5);new Thread(() -> {wn.print("a", 1, 2);}).start();new Thread(() -> {wn.print("b", 2, 3);}).start();new Thread(() -> {wn.print("c", 3, 1);}).start();}}/*输出内容 等待标记下一个标记a 1 2b 2 3c 3 1*/class WaitNotify {// 打印a 1 2public void print(String str, int waitFlag, int nextFlag) {for (int i = 0; i < loopNumber; i++) {synchronized (this) {while(flag != waitFlag) {try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}System.out.print(str);flag = nextFlag;this.notifyAll();}}}// 等待标记private int flag; // 2// 循环次数private int loopNumber;public WaitNotify(int flag, int loopNumber) {this.flag = flag;this.loopNumber = loopNumber;}}

使用park,unpark实现线程交替执行例子:

public class Test31 {static Thread t1;static Thread t2;static Thread t3;public static void main(String[] args) {ParkUnpark pu = new ParkUnpark(5);t1 = new Thread(() -> {pu.print("a", t2);});t2 = new Thread(() -> {pu.print("b", t3);});t3 = new Thread(() -> {pu.print("c", t1);});t1.start();t2.start();t3.start();LockSupport.unpark(t1);}}class ParkUnpark {public void print(String str, Thread next) {for (int i = 0; i < loopNumber; i++) {LockSupport.park();System.out.print(str);LockSupport.unpark(next);}}private int loopNumber;public ParkUnpark(int loopNumber) {this.loopNumber = loopNumber;}}

参考视频:/video/BV16J411h7Rd

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。