package test;
import java.util.concurrent.CountDownLatch;
/**
*
* @author frank
*
* 面试考题:编写4个线程,名称分别为A,B,C,D,4个线程永久循环执行,且这4个线程永久按照A B C D的顺序打印。
* 编程思路:设置4个锁,一开始4个线程同时锁住,然后主线程释放第一个线程锁,则第1个线程开始执行,执行完毕后释放第2个线程的锁,同时给自己线程再加锁,
* 此时第2个线程开始执行,执行完毕后释放第3个线程的锁,同时给自己线程再加锁,
* 此时第3个线程开始执行,执行完毕后释放第4个线程的锁,同时给自己线程再加锁,
* 此时第4个线程开始执行,执行完毕后释放第1个线程的锁,同时给自己线程再加锁。
* 以上循环永久执行下去。
*
*/
public class ThreadSample {
static CountDownLatch[] locks = new CountDownLatch[4];
public static void main(String[] args) {
// TODO Auto-generated method stub
for (int i = 0; i < locks.length; i++) {
locks[i] = new CountDownLatch(1);
}
String[] names = new String[] { "A", "B", "C", "D" };
for (int i = 0; i < 4; i++) {
Thread t = new myThread(names[i], i);
t.start();
}
locks[0].countDown();
System.out.println("Main Thread finished.");
}
}
class myThread extends Thread {
String name;
int index;
public myThread(String name, int index) {
super();
this.name = name;
this.index = index;
System.out.println("name=" + name + " index=" + index);
}
@Override
public void run() {
try {
while (true) {
ThreadSample.locks[index].await();
System.out.println(name);
Thread.sleep(500);
int n = (index + 1) % 4;
System.out.println(name + "--->index:" + n);
ThreadSample.locks[index] = new CountDownLatch(1);
ThreadSample.locks[n].countDown();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}