方法一:
public class PrintABC {
public static void main(String[] args) {
final Lock lock = new ReentrantLock();
Thread a = new Thread(new PrintfABCThread("A", lock, 0));
Thread b = new Thread(new PrintfABCThread("B", lock, 1));
Thread c = new Thread(new PrintfABCThread("C", lock, 2));
a.start();
b.start();
c.start();
}
}
class PrintfABCThread implements Runnable {
private String name;
private Lock lock;
private Integer flag;
public static int count = 0;
public static final int MAX = 30;
public PrintfABCThread(String name, Lock lock, Integer flag) {
this.name = name;
this.lock = lock;
this.flag = flag;
}
@Override
public void run() {
while (true) {
lock.lock();
if (count >= MAX) {
lock.unlock();
return;
}
if (count % 3 == flag) {
System.out.print(name);
count++;
}
lock.unlock();
}
}
}
方法二:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class printABC {
private static Lock lock=new ReentrantLock();
private static int state=0;
static class ThreadA extends Thread{
@Override
public void run(){
for(int i=0;i<10;) {
lock.lock();
if (state % 3 == 0) {
System.out.print("A");
state++;
i++;
}
lock.unlock();
}
}
}
static class ThreadB extends Thread{
@Override
public void run(){
for(int i=0;i<10;) {
lock.lock();
if (state % 3 == 1) {
System.out.print("B");
state++;
i++;
}
lock.unlock();
}
}
}
static class ThreadC extends Thread{
@Override
public void run(){
for(int i=0;i<10;) {
lock.lock();
if (state % 3 == 2) {
System.out.print("C");
state++;
i++;
}
lock.unlock();
}
}
}
public static void main(String args[]){
new ThreadA().start();
new ThreadB().start();
new ThreadC().start();
}
}