import java.util.concurrent.locks.ReentrantLock;
public class PrintABC {
public static final ReentrantLock lock = new ReentrantLock();
public static char cnt = 'A';
public static int times = 0;
public static void main(String[] args) {
new Thread(new Ap()).start();
new Thread(new Bp()).start();
new Thread(new Cp()).start();
}
static class Ap implements Runnable{
@Override
public void run() {
while(true){
go();
}
}
private void go(){
try{
lock.lock();
if(cnt == 'A' && times < 30){
System.out.print(Thread.currentThread().getName()
+"---print---A---");
cnt = 'B';
times++;
System.out.println(times);
}
}catch(Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
static class Bp implements Runnable{
@Override
public void run() {
while(true){
go();
}
}
private void go(){
try{
lock.lock();
if(cnt == 'B' && times < 30){
System.out.print(Thread.currentThread().getName()
+"---print---B---");
cnt = 'C';
times++;
System.out.println(times);
}
}catch(Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
static class Cp implements Runnable{
@Override
public void run() {
while(true){
go();
}
}
private void go(){
try{
lock.lock();
if(cnt == 'C' && times < 30){
System.out.print(Thread.currentThread().getName()
+"---print---C---");
cnt = 'A';
times++;
System.out.println(times);
}
}catch(Exception e){
e.printStackTrace();
}finally {
lock.unlock();
}
}
}
}
弱智三個線程輪流打印ABC
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.