mam 3 wątki 1st Drukowanie 2-ta druk B 3rd drukowania Curuchomione 3 wątki w sekwencji java
Chcę drukować w sekwencji ABCABCABC i tak dalej .....
Więc napisał poniższy program, ale nie jestem w stanie osiągnąć tego samego. Jestem świadomy problemu, że gdy status = 1 w tym czasie mówi na przykład wątek B1 i C1 oczekują i kiedy robię notifyAll() obu oczekujących wątku obudzić iw zależności od przydziału procesora może wydrukować B lub C.
w tym przypadku chcę wydrukować tylko B po A.
jakie modyfikacje muszę wykonać.
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());
}
}
}
AMHO odpowiedzi są właściwe, ale można zoptymalizować ten kod z instancji: trzy klasy są to samo z wyjątkiem wartości literalnej statusu. Możesz dodać parametr, sugeruję executionOrder, aby miał tylko jedną klasę. Nadaj nazwę wątkowi za pomocą funkcji setName() lub super() i użyj jej w raporcie wyjątku. – Aubin
prawda ... zoptymalizuję to ... dzięki Aubin. – Jayesh