import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* abc用锁控制顺序打印
*/
public class ABCTest {
static Object syn = new Object();
public static String next = "a";
public static void main(String[] args) {
new ABCTest().print();
}
private void print() {
ExecutorService service = Executors.newFixedThreadPool(3);
service.execute(new APrintThread());
service.execute(new BPrintThread());
service.execute(new CPrintThread());
}
class APrintThread implements Runnable {
@Override
public void run() {
while (true) {
synchronized (syn) {
while (!"a".equals(next)) {
try {
syn.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.print("a");
next = "b";
syn.notifyAll();
}
}
}
}
//
class BPrintThread implements Runnable {
@Override
public void run() {
while (true) {
synchronized (syn) {
while (!"b".equals(next)) {
try {
syn.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.print("b");
next = "c";
syn.notifyAll();
}
}
}
}
//
class CPrintThread implements Runnable {
@Override
public void run() {
while (true) {
synchronized (syn) {
while (!"c".equals(next)) {
try {
syn.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("c");
next = "a";
syn.notifyAll();
}
}
}
}
}
线程锁控制abc顺序打印
最新推荐文章于 2023-06-22 13:01:04 发布