线程轮循打印ABC...

 package com.java.concurrent;

 import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock; /**
* 使用多线程的方式进行轮循打印ABCABC
* @author fliay
*
*/
public class TestABCAlternate { public static void main(String[] args) {
final AlternateDemo ad = new AlternateDemo();
new Thread(new Runnable() { public void run() {
for(int i = ;i<;i++){
try {
ad.loopA(i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
},"线程1").start(); new Thread(new Runnable() { public void run() {
for(int i = ;i<;i++){
try {
ad.loopB(i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
},"线程2").start(); new Thread(new Runnable() { public void run() {
for(int i = ;i<;i++){
try {
ad.loopC(i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
},"线程3").start(); } } class AlternateDemo{ private int number=;//当前正在执行的线程标记 private Lock lock = new ReentrantLock(); private Condition condition1 = lock.newCondition();
private Condition condition2 = lock.newCondition();
private Condition condition3 = lock.newCondition(); public void loopA(int totalLoop) throws InterruptedException{
lock.lock();
try{
//1.判断
if(number!=){
condition1.await();
}
//2.打印
System.out.println(Thread.currentThread().getName()+":A"+"-"+totalLoop); //3.唤醒
number=;
condition2.signal();
}finally{
lock.unlock();
}
} public void loopB(int totalLoop) throws InterruptedException{
lock.lock();
try{
//1.判断
if(number!=){
condition2.await();
}
//2.打印
System.out.println(Thread.currentThread().getName()+":B"+"-"+totalLoop); //3.唤醒
number=;
condition3.signal();
}finally{
lock.unlock();
}
} public void loopC(int totalLoop) throws InterruptedException{
lock.lock();
try{
//1.判断
if(number!=){
condition3.await();
}
//2.打印
System.out.println(Thread.currentThread().getName()+":C"+"-"+totalLoop); //3.唤醒
number=;
condition1.signal();
}finally{
lock.unlock();
}
} }
上一篇:Android 屏幕旋转 处理 AsyncTask 和 ProgressDialog 的最佳方案


下一篇:ubuntu16.04搭建ftp服务器