简单粗暴直接上代码。
public class ThreadTest2 {
public synchronized void increateNum(int count) {
try {
this.notify();
System.out.println(Thread.currentThread().getName()+"="+ count);
this.wait();
} catch (Exception e) {
}
}
public static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(100);
ThreadTest2 threadTest2 = new ThreadTest2();
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 100; i+=2) {
countDownLatch.countDown();
threadTest2.increateNum(i+1);
}
}
});
thread.setName("thread1");
thread.start();
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 1; i < 100; i+=2) {
countDownLatch.countDown();
threadTest2.increateNum(i+1);
}
}
});
thread1.setName("thread2");
thread1.start();
countDownLatch.await();
System.out.println("--两个线程执行完毕--");
thread.interrupt();
thread1.interrupt();
System.out.println("———终止所有线程——");
}
}
网友评论