今天看了一个帖子,https://blog.csdn.net/jiaobuchong/article/details/86555208
想回复他,但代码没贴成功,就另开个帖子。
愿问题:编写一个程序,开启 3 个线程,这三个线程的 名字 分别为 A、B、C,每个线程将自己的 名字 在屏幕上打印 10 遍,要求输出的结果必须按顺序显示。如:ABCABCABC……
我直接贴代码吧。
package cn.tx.thread.printsequencely;
public class PrintSequencely implements Runnable {
static Object oLock = new Object();
static int nSequence = 0;
int nMySequence = 0;
public PrintSequencely(int nMySequence) {
this.nMySequence = nMySequence;
}
@Override
public void run() {
for (int i = 0; i < 10; i++) {
synchronized (oLock) {
while (nSequence % 3 != nMySequence) {
try {
oLock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.print(Thread.currentThread().getName());
nSequence++;
oLock.notifyAll();
}
}
}
public static void main(String[] args) {
PrintSequencely A = new PrintSequencely(0);
PrintSequencely B = new PrintSequencely(1);
PrintSequencely C = new PrintSequencely(2);
Thread ta = new Thread(A);
Thread tb = new Thread(B);
Thread tc = new Thread(C);
ta.setName("A");
tb.setName("B");
tc.setName("C");
ta.start();
tb.start();
tc.start();
}
}