问题描述
我有3个主题
第一次印刷A
第二次印刷B
第3次印刷C
I have 3 threads1st printing A2nd printing B3rd printing C
我想按顺序打印ABCABCABC等等......
I want to print in sequence A B C A B C A B C and so on.....
所以我编写了下面的程序,但我无法实现同样的目标。
我知道当status = 1的时候说例如B1和C1线程正在等待,当我执行notifyAll()时,两个等待线程唤醒并根据CPU分配它可能会打印B或C 。
So I wrote the program below, but I am not able to achieve the same.I am aware of the problem that when status=1 at that time say for example B1 and C1 thread are waiting and when I do notifyAll() both waiting thread wake up and depending on CPU allocation it might print B or C.
在这种情况下,我只希望在A之后打印B。
in this case I want only B to be printed after A.
我需要做什么修改。
public class NotifyAllExample {
int status=1;
public static void main(String[] args) {
NotifyAllExample notifyAllExample = new NotifyAllExample();
A1 a=new A1(notifyAllExample);
B1 b=new B1(notifyAllExample);
C1 c=new C1(notifyAllExample);
a.start();
b.start();
c.start();
}
}
class A1 extends Thread{
NotifyAllExample notifyAllExample;
A1(NotifyAllExample notifyAllExample){
this.notifyAllExample = notifyAllExample;
}
@Override
public void run() {
try{
synchronized (notifyAllExample) {
for (int i = 0; i < 100; i++) {
if(notifyAllExample.status!=1){
notifyAllExample.wait();
}
System.out.print("A ");
notifyAllExample.status = 2;
notifyAllExample.notifyAll();
}
}
}catch (Exception e) {
System.out.println("Exception 1 :"+e.getMessage());
}
}
}
class B1 extends Thread{
NotifyAllExample notifyAllExample;
B1(NotifyAllExample notifyAllExample){
this.notifyAllExample = notifyAllExample;
}
@Override
public void run() {
try{
synchronized (notifyAllExample) {
for (int i = 0; i < 100; i++) {
if(notifyAllExample.status!=2){
notifyAllExample.wait();
}
System.out.print("B ");
notifyAllExample.status = 3;
notifyAllExample.notifyAll();
}
}
}catch (Exception e) {
System.out.println("Exception 2 :"+e.getMessage());
}
}
}
class C1 extends Thread{
NotifyAllExample notifyAllExample;
C1(NotifyAllExample notifyAllExample){
this.notifyAllExample = notifyAllExample;
}
@Override
public void run() {
try{
synchronized (notifyAllExample) {
for (int i = 0; i < 100; i++) {
if(notifyAllExample.status!=3){
notifyAllExample.wait();
}
System.out.print("C ");
notifyAllExample.status = 1;
notifyAllExample.notifyAll();
}
}
}catch (Exception e) {
System.out.println("Exception 3 :"+e.getMessage());
}
}
}
推荐答案
将这些IF语句转换为WHILE语句以获得所需的行为:
Convert those IF statements to WHILE statements to get the desired behavior:
if (notifyAllExample.status != 2){
notifyAllExample.wait();
}
到
while (notifyAllExample.status != 2){
notifyAllExample.wait();
}
这将确保如果线程被通知,它将不会消失while循环直到状态值是它所期望的。
This will ensure that if a thread is notified, it won't go out of the while loop until the status value is what it expects.
另外,将 status
标记为volatile,以便线程没有本地副本。
Also, mark status
as volatile so that the threads won't have a local copy.
这篇关于按顺序java运行3个线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!