package test5; import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock; class PrintThread implements Runnable{ private ReentrantLock lock=new ReentrantLock();
Condition condition = lock.newCondition();
private int state=0; @Override
public void run() {
String threadName=Thread.currentThread().getName();
lock.lock();
try {
for(int i=0;i<9;i++){
if(threadName.equals("A")){
while(state%3!=0){
condition.await();
}
}else if(threadName.equals("B")){
while(state%3!=1){
condition.await();
}
}else if(threadName.equals("C")){
while(state%3!=2){
condition.await();
}
}
state++;
System.out.println(threadName);
condition.signalAll();
}
} catch (Exception e) {
// TODO: handle exception
}finally{
lock.unlock();
} } } public class PrintABC{
public static void main(String[] args) {
PrintThread pt=new PrintThread();
Thread t1=new Thread(pt,"A");
Thread t2=new Thread(pt,"B");
Thread t3=new Thread(pt,"C");
t1.start();
t2.start();
t3.start();
}
}
一条线程连续打印ABC:
class PrintABC implements Runnable{ private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition(); @Override
public void run() {
String threadName = Thread.currentThread().getName();
lock.lock();
int state = 0;
try{
while(state < 10){
if(state % 3 == 0){
System.out.print("A ");
}else if(state % 3 == 1){
System.out.print("B ");
}else if(state % 3 == 2){
System.out.print("C ");
}
state++;
} }finally {
lock.unlock();
}
} }
public class ThreadDemo { public static void main(String[] args) {
PrintABC p = new PrintABC();
Thread t = new Thread(p);
t.start();
}
}