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();
}
}
}
}
要点:
1 用new 三个thread实现,每一个thread的构造器里new各自的类,外部测试类,要有3个静态变量,一把final的lock,一个static的cnt 代表当前字符,一个static count 代表运行次数
2 每个类都是静态的,实现Runnable接口,重写run方法,run方法里写死while,循环内部运行私有方法
3 私有方法里要用try catch 包裹,并且finally最后要释放锁,方法内部先去看cnt是否是与当前线程匹配的变量,循环次数是不是到达上限,if条件达到之后,打印当前线程name 输出cnt,之后改cnt的值,然后count++,释放锁之后,结束