Ho scritto un programma in cui sono in esecuzione due thread, ecco perché ho utilizzato la parola chiave sincronizzata. Il mio codice è sotto-perché il metodo sincronizzato non funziona per il multithread
public class TestThreadAnother {
public synchronized void decrement(){
try {
for (int i = 4; i > 0; i--) {
System.out.println("Thread " + i);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class TestThreadClass extends Thread {
private String threadName;
TestThreadAnother obj1;
public TestThreadClass(String threadName, TestThreadAnother Obj1) {
this.threadName = threadName;
obj1 = Obj1;
System.out.println("Creating " + threadName);
}
@Override
public void run() {
System.out.println("Running " + threadName);
obj1.decrement();
System.out.println("End of " + threadName);
}
}
public class TestThreadMain {
public static void main(String[] args) {
TestThreadAnother obj1 = new TestThreadAnother();
TestThreadClass t1 = new TestThreadClass("Thread 1", obj1);
TestThreadClass t2 = new TestThreadClass("Thread 2", obj1);
t1.start();
t2.start();
}
}
L'uscita shoud essere -
Creating Thread 1
Creating Thread 2
Running Thread 1
Thread 4
Thread 3
Thread 2
Thread 1
End of Thread 1
Running Thread 2
Thread 4
Thread 3
Thread 2
Thread 1
End of Thread 2
Ma sto ottenendo il seguente risultato-
Creating Thread 1
Creating Thread 2
Running Thread 2
Thread 4
Thread 3
Running Thread 1
Thread 2
Thread 1
Thread 4
Thread 3
Thread 2
Thread 1
End of Thread 1
End of Thread 2
ma la mia domanda è come io sto usando metodo sincronizzato poi perché questo sta accadendo? Come sapere se io uso sincronizzato, allora al primo thread verrà eseguito e poi verrà eseguito il secondo. Ma nel mio caso a volte questo non sta accadendo. Gli esperti Java hanno bisogno del tuo aiuto per quanto riguarda questo problema.
solo dopo Thread2 completato il metodo decremento, Thread1 eseguito lo stesso metodo-perché solo il metodo è sincronizzato –
Cosa si aspetta il try/catch in 'decremento()' per catturare? –