有三个线程,a、b、c,a打印“T1”,b打印“T2”,c打印“T3”,a执行完后,b执行;b执行完后,c执行。如此循环100遍
有三个线程,a、b、c,a打印“T1”,b打印“T2”,c打印“T3”,a执行完后,b执行;b执行完后,c执行。如此循环100遍。
package com.company; /** * 测试三个线程协同运行 * * @Auther: xxx * @Date: Created In 2018/1/1 22:18 * @Modified By: */ public class TestThread { public static void main(String[] args) { Thread1 t1 = new Thread1("T1"); Thread1 t2 = new Thread1("T2"); Thread1 t3 = new Thread1("T3"); t1.setNotifySignalLight(t2.getSignalLight()); t2.setNotifySignalLight(t3.getSignalLight()); t3.setNotifySignalLight(t1.getSignalLight()); t1.start(); t2.start(); t3.start(); t1.getSignalLight().notifyThis(); } } /** * 执行打印任务线程 */ class Thread1 extends Thread { //当前线程的信号灯 private SignalLight signalLight = new SignalLight(); //需要打印的消息 private String msg; /** * 当前线程的信号灯 * * @return */ public SignalLight getSignalLight() { return signalLight; } //当前线程需要指示其他线程的信号灯 private SignalLight notifySignalLight = null; /** * 设置其他线程的信号灯 * @param notifySignalLight */ public void setNotifySignalLight(SignalLight notifySignalLight) { this.notifySignalLight = notifySignalLight; } /** * 构造函数 * @param msg 打印的消息 */ public Thread1(String msg) { this.msg = msg; } /** * 线程的执行体 */ @Override public void run() { for (int i = 0; i < 100; i++) { this.signalLight.print(msg); this.notifySignalLight.notifyThis(); } } } /** * 信号灯类 */ class SignalLight { //是否打印消息,默认不打印,再线程外,发送消息打印 private boolean isPass = false; /** * 打印消息 * @param msg */ public synchronized void print(String msg) { //如果isPass == false,则线程等待信号,才能执行 if (!isPass) { try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } if (isPass) System.out.println(msg); this.isPass = false; } /** * 通知当前线程,可以执行 */ public synchronized void notifyThis() { this.isPass = true; this.notify(); } }