1、使用线程池管理线程。
2、使用synchronized实现线程间同步。
3、使用wait()方法让当前线程等待;使用notify()方法唤起wait中的线程。
4、使用CountDownLatch等待线程结束。
上代码
- package com.thread;
-
- import java.util.concurrent.CountDownLatch;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.TimeUnit;
-
- public class TasksCommunicate extends Thread {
- private static final int size = 12;
- private static StringBuilder sb = new StringBuilder();
- private static Integer num = 0;
- private String name;
- private CountDownLatch countDownLatch;
-
- public TasksCommunicate(String name, CountDownLatch countDownLatch) {
- this.name = name;
- this.countDownLatch = countDownLatch;
- }
-
- @Override
- public void run() {
- while (num < size) {
- synchronized (TasksCommunicate.class) {
- num = num + 1;
- System.out.println("thread_" + name + " 打印:" + sb.toString());
- sb = new StringBuilder("thread_" + name + "已完成自增1,目前num=" + num + ",请知晓!");
- TasksCommunicate.class.notify();
- try {
- if (num < size) {
- TasksCommunicate.class.wait();
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- }
- }
- countDownLatch.countDown();
- System.out.println("thread_" + name + " 结束!");
- }
-
- public static void main(String[] args) {
- CountDownLatch countDownLatch = new CountDownLatch(2);
- Thread thread0 = new TasksCommunicate("A", countDownLatch);
- Thread thread1 = new TasksCommunicate("B", countDownLatch);
-
- ExecutorService executor = Executors.newFixedThreadPool(2);
-
- executor.submit(thread0);
- executor.submit(thread1);
-
- try {
- countDownLatch.await(3, TimeUnit.SECONDS);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
-
- executor.shutdown();
- System.out.println("进程结束,退出!!!");
- }
- }
打印输出:
thread_A 打印:
thread_B 打印:thread_A已完成自增1,目前num=1,请知晓!
thread_A 打印:thread_B已完成自增1,目前num=2,请知晓!
thread_B 打印:thread_A已完成自增1,目前num=3,请知晓!
thread_A 打印:thread_B已完成自增1,目前num=4,请知晓!
thread_B 打印:thread_A已完成自增1,目前num=5,请知晓!
thread_A 打印:thread_B已完成自增1,目前num=6,请知晓!
thread_B 打印:thread_A已完成自增1,目前num=7,请知晓!
thread_A 打印:thread_B已完成自增1,目前num=8,请知晓!
thread_B 打印:thread_A已完成自增1,目前num=9,请知晓!
thread_A 打印:thread_B已完成自增1,目前num=10,请知晓!
thread_B 打印:thread_A已完成自增1,目前num=11,请知晓!
thread_A 结束!
thread_B 结束!
进程结束,退出!!!