通過控制變量的方式
public class Test {
public static int num = 1;
public static void main(String[] args) {
Thread a = new Thread(new Runnable() {
@Override
public void run(){
while (true){
if(num == 30){
break;
}
if(num % 3 == 1){
System.out.println("A");
num++;
}
}
}
});
Thread b = new Thread(new Runnable() {
@Override
public void run(){
while (true){
if(num == 30){
break;
}
if(num % 3 == 2){
System.out.println("B");
num++;
}
}
}
});
Thread c = new Thread(new Runnable() {
@Override
public void run(){
while (true){
if(num == 30){
break;
}
if(num % 3 == 0){
System.out.println("C");
num++;
}
}
}
});
a.start();
b.start();
c.start();
}
}
通過用synchronized、wait、notifyAll實現
public class Test {
public static int num = 1;
public static class Pabc implements Runnable{
private int id;
private char[] ch = { 'C', 'A', 'B' };
public Pabc(int id){
this.id = id;
}
@Override
public void run(){
while (num <= 30){
synchronized (Pabc.class){
if (num % 3 == id){
System.out.println(ch[id]);
num++;
Pabc.class.notifyAll();
}else{
try {
Pabc.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
public static void main(String[] args) {
new Thread(new Pabc(1)).start();
new Thread(new Pabc(2)).start();
new Thread(new Pabc(0)).start();
}
}
Condition 和 Lock 一起使用
public static int num = 1;
final static ReentrantLock lock = new ReentrantLock();
final static Condition condition = lock.newCondition();
public static class Pabc implements Runnable{
private int id;
private char[] ch = { 'C', 'A', 'B' };
public Pabc(int id){
this.id = id;
}
@Override
public void run(){
lock.lock();
try {
while (num <= 30){
if(num % 3 != id){
condition.await();
}else{
System.out.println(ch[id]);
num++;
condition.signalAll();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
public static void main(String[] args) {
new Thread(new Pabc(1)).start();
new Thread(new Pabc(2)).start();
new Thread(new Pabc(0)).start();
}