Java并发:三个线程轮流打印十次abc
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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的主要内容,如果未能解决你的问题,请参考以下文章