参考:https://blog.csdn.net/qq_41384351/article/details/91447089
三个线程ID为ABC,每个将自己的ID在屏幕打印10遍,结果按ABCABC...样式显示
ThreadTest.java
package jvm;
/*
* 三个线程ID为ABC,每个将自己的ID在屏幕打印10遍,结果按ABCABC...样式显示
* */
public class ThreadTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
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();
}
}
ThreadName.java
package jvm;
public class ThreadName {
private int index;//当前执行线程ID
public int getIndex() {
return index;
}
public void setIndex(int index) {
this.index = index;
}
}
ThreadDemo.java
package jvm;
public class ThreadDemo extends Thread {
private int threadNum;// 当前线程编号
private ThreadName threadName;// 线程间传递对象
public ThreadDemo(int 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++;
}
}
}
}
1073

被折叠的 条评论
为什么被折叠?



