一、如图
文章图片
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;
}
}
运行结果:
文章图片
推荐阅读
- 代码狂魔|实战证明java中的两把锁ReentrantLock与synchronized的系统调用
- 进程通信方式
- 解决方案|大文件拆分方案的java实践
- 多线程编程(1)(共享内存与锁)
- Java|多线程编程(二)——面试题,每个线程只打印一种字符,多个线程协同顺序打印n次字符串(求大神的其他实现方案)
- 一道面试题(多个线程按顺序输出)
- 多线程|java多线程实现奇偶数输出
- 面试题--三个线程循环打印ABC 10次(另类解决方法)
- 用信号量(互斥锁)实现两个线程交替打印