package t1t2t3t4; /** * Created by Administrator on 2017/5/13. */ public class Main { public static void main(String[] args) { Object lock = new Object(); for(int i=1;i<=4;i++){ char str=(char) (64+i); System.out.print(str+":"); NumberThread n = new NumberThread(); n.state=i; Thread t1 = new Thread(n); t1.setName("线程1"); Thread t2 = new Thread(n); t2.setName("线程2"); Thread t3 = new Thread(n); t3.setName("线程3"); Thread t4 = new Thread(n); t4.setName("线程4"); t1.start();t2.start();t3.start();t4.start(); try { Thread.sleep(500); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(); } } }package t1t2t3t4; /** * Created by Administrator on 2017/5/13. */ public class NumberThread implements Runnable { int count = 0; int state = 1; //记录当前要执行的线程 public void run() { while (true) { //传对象,通过锁这个对象,判断资源的锁定状态 synchronized (this) { //如果线程名中包含state,表示线程名正确,打印数字 if (Thread.currentThread().getName().contains(state + "")) { System.out.print(state); //正确线程打印一次后,增加state,用于下次正确的线程打印 count++; state++; }else{ //要运行的线程和state不一致,则休眠, 等待下次唤醒 try { wait(); } catch (InterruptedException e) { } } //state加到4,从1开始 if (state == 5) { state = 1; //通知其他所有线程运行。不知道运行的是哪个线程 } //唤醒所有线程 notifyAll(); if (count == 12) { break; } } } } }运行结果:
A:123412341234
B:234123412341
C:341234123412
D:412341234123
四个线程t1,t2,t3,t4,分别打印文字,t1只能打印1,t2只能打印2,t3只能打印3,t4只能打印4,打印如下A B C D内容: A:123412341234 B:234123412341
最新推荐文章于 2021-12-24 21:24:49 发布