0 点赞 评论 收藏
分享
0 点赞 评论 收藏
分享
2018-03-14 23:03
西南大学 Java antibody:public static void main(String[] args) throws InterruptedException {
final int PRINT_TIMES = 3;
final int THREADS_NUMBER = 4;
CountDownLatch latch = new CountDownLatch(THREADS_NUMBER);
Object[] locks = new Object[THREADS_NUMBER];
for (int i = 0; i < locks.length; i++) {
locks[i] = new Object();
}
for (int i = 0; i < locks.length; i++) {
new MyThread(locks[i], locks[(i + 1) % locks.length],
PRINT_TIMES, (char) ('A' + i), latch)
.start();
}
// 确认所有子线程已处于等待状态
latch.await();
synchronized (locks[0]) {
locks[0].notify();
}
}
private static class MyThread extends Thread {
final Object lock;
final Object nextLock;
int printTime;
char c;
CountDownLatch latch;
MyThread(Object lock, Object nextLock, int printTime,
char c, CountDownLatch latch) {
this.lock = lock;
this.nextLock = nextLock;
this.printTime = printTime;
this.latch = latch;
this.c = c;
}
public void run() {
synchronized (lock) {
for (int i = 0; i < printTime; i++) {
latch.countDown();
try {
// 等待当前线程被唤醒
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
// 输出并唤醒下一线程
System.out.println(c);
synchronized (nextLock) {
nextLock.notify();
}
}
}
synchronized (nextLock) {
nextLock.notify();
}
}
}
投递华为等公司10个岗位 >
0 点赞 评论 收藏
分享
0 点赞 评论 收藏
分享
关注他的用户也关注了: