package JUC;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 編寫一個(gè)程序開啟三個(gè)線程分別為ABC,每個(gè)線程將自己的Id在屏幕上打印十次,要求輸出結(jié)果必須按照順序ABCABCABC....
*/
public class TestAlternate {
public static void main(String[] args){
final Alternate ad =new Alternate();
? ? ? new Thread(new Runnable() {
@Override
? ? ? ? ? public void run() {
for (int j=1;j<=20;j++) {
ad.functionA(j);
? ? ? ? ? ? ? }
}
},"A").start();
? ? ? ? new Thread(new Runnable() {
@Override
? ? ? ? ? ? public void run() {
for (int j=1;j<=20;j++) {
ad.functionB(j);
? ? ? ? ? ? ? ? }
}
},"B").start();
? ? ? ? new Thread(new Runnable() {
@Override
? ? ? ? ? ? public void run() {
for (int j=1;j<=20;j++) {
ad.functionC(j);
? ? ? ? ? ? ? ? }
}
},"C").start();
? ? }
}
class Alternate? {
int number =1 ;
? ? Locklock =new ReentrantLock();
? ? Conditioncondition1 =lock.newCondition();
? ? Conditioncondition2 =lock.newCondition();
? ? Conditioncondition3 =lock.newCondition();
? ? void functionA(int loapTime){
try{
lock.lock();
? ? ? ? ? ? if (number!=1){
condition1.await();
? ? ? ? ? ? }
for (int i=1; i<=10;i++){
System.out.println(Thread.currentThread().getName()+":"+"\t"+i+"\t"+loapTime);
? ? ? ? ? ? }
number =2;
? ? ? ? ? ? condition2.signal();
? ? ? ? }catch (InterruptedException e){
}finally {
lock.unlock();
? ? ? ? }
}
void functionB(int loapTime){
try{
lock.lock();
? ? ? ? ? ? if (number!=2){
condition2.await();
? ? ? ? ? ? }
for (int i=1; i<=10;i++){
System.out.println(Thread.currentThread().getName()+":"+"\t"+i+"\t"+loapTime);
? ? ? ? ? ? }
number =3;
? ? ? ? ? ? condition3.signal();
? ? ? ? }catch (InterruptedException e){
}finally {
lock.unlock();
? ? ? ? }
}
void functionC(int loapTime){
try{
lock.lock();
? ? ? ? ? ? if (number!=3){
condition3.await();
? ? ? ? ? ? }
for (int i=1; i<=10;i++){
System.out.println(Thread.currentThread().getName()+":"+"\t"+i+"\t"+loapTime);
? ? ? ? ? ? }
number =1;
? ? ? ? ? ? condition1.signal();
? ? ? ? }catch (InterruptedException e){
}finally {
lock.unlock();
? ? ? ? }
}
}