日常练习题|三个线程ID为ABC,每个将自己的ID在屏幕打印10遍,结果按ABCABC...样式显示

一、如图
日常练习题|三个线程ID为ABC,每个将自己的ID在屏幕打印10遍,结果按ABCABC...样式显示
文章图片

ABCABCMain.java

package PrintABC; public class ABCABCMain { public static void main(String[] args) { ThreadName threadName = new ThreadName(); threadName.setIndex(0); Thread thread0 = new Thread(new ThreadDemo(0, threadName)); Thread thread1 = new Thread(new ThreadDemo(1,threadName)); Thread thread2 = new Thread(new ThreadDemo(2,threadName)); thread0.setName("A"); thread1.setName("B"); thread2.setName("C"); thread0.start(); thread1.start(); thread2.start(); } }

【日常练习题|三个线程ID为ABC,每个将自己的ID在屏幕打印10遍,结果按ABCABC...样式显示】ThreadDemo.java
package PrintABC; public class ThreadDemo extends Thread { private Integer threadNum; //当前线程编号 private ThreadName threadName; //线程间传递对象 public ThreadDemo(Integer threadNum, ThreadName threadName){ this.threadName = threadName; this.threadNum = threadNum; }@Override public void run() { int i = 1; while (i <= 10) { synchronized (threadName) { while (threadNum != threadName.getIndex()) { try { threadName.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.print(Thread.currentThread().getName()); threadName.setIndex((threadNum+1)%3); threadName.notifyAll(); i++; } }} }

ThreadName.java
package PrintABC; public class ThreadName { private Integer index; //当前执行线程ID public Integer getIndex() { return index; }public void setIndex(Integer index) { this.index = index; } }

运行结果:
日常练习题|三个线程ID为ABC,每个将自己的ID在屏幕打印10遍,结果按ABCABC...样式显示
文章图片

    推荐阅读