Ho il seguente programma nello stesso file. Ho sincronizzato il metodo run().perché il metodo sincronizzato consente l'esecuzione contemporanea di più thread?
class MyThread2 implements Runnable {
Thread t;
MyThread2(String s) {
t=new Thread(this,s);
t.start();
}
public synchronized void run() {
for (int i=0;i<3;i++) {
System.out.println("Thread name : "+ Thread.currentThread).getName());
try {
t.sleep(1000);
}
catch (InterruptedException e) {
e.getMessage();
}
}
}
}
class TestSync {
public static void main(String[] args) {
MyThread2 m1=new MyThread2("My Thread 1");
c.fun();
}
}
class c {
static void fun() {
MyThread2 m1=new MyThread2("My Thread 4");
}
}
uscita è
Thread name : My Thread 1
Thread name : My Thread 4
Thread name : My Thread 4
Thread name : My Thread 1
Thread name : My Thread 1
Thread name : My Thread 4
mia domanda è perché è il metodo che consente sia "My filettatura 1" e "My filettatura 4" accesso filo contemporaneamente sincronizzato?
Il codice che hai postato ha almeno una sintassi errore, ed è davvero difficile da leggere come è. Assicurati di pubblicare il tuo codice reale e prova a formattarlo in modo leggibile. – Mat
L'equivoco è che si sta bloccando un metodo, invece si dispone di un metodo che blocca l'istanza. –