首页 > 代码库 > Java并发:三个线程轮流打印十次abc
Java并发:三个线程轮流打印十次abc
方法1:用synchronized、wait、notifyAll实现
public class Main {
static boolean t1Running = true;
static boolean t2Running = false;
static boolean t3Running = false;
public static void main(String[] args) throws InterruptedException {
final Object lock = new Object();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (lock) {
while (!t1Running) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("a");
t1Running = false;
t2Running = true;
t3Running = false;
lock.notifyAll();
}
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (lock) {
while (!t2Running) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("b");
t1Running = false;
t2Running = false;
t3Running = true;
lock.notifyAll();
}
}
}
});
Thread t3 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (lock) {
while (!t3Running) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
t1Running = true;
t2Running = false;
t3Running = false;
System.out.println("c");
lock.notifyAll();
}
}
}
});
t1.start();
t2.start();
t3.start();
}
}
Java并发:三个线程轮流打印十次abc
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。