bouali mohamed amine bouali mohamed amine - 1 month ago 17
Java Question

Java - parallel processing deadlock

I want try simple Deadlock example. I know the problem is in

(Thread t1 = new Thread() { )
and
( Thread t1 = new Thread() { )
.


The value of the local variable t1 is not used.


But I can't fix it.

public static void main(String[] args) {

final String passenger1 ="pick passenger1";
final String passenger2 ="pick passenger2";

Thread t1 = new Thread() {
public void run(){
synchronized (passenger1) {

System.out.println("Thread 1: locked passenger1 ");

try { Thread.sleep(100);} catch (Exception e) {}
System.out.println("Thread 1: waiting to get passenger 2 ");
synchronized (passenger2) {
System.out.println("Thread 1: locked passenger 2");
} } } };

Thread t2 = new Thread() {

public void run() {
synchronized (passenger2) {

System.out.println("Thread 2: locked passenger2 ");

try { Thread.sleep(100);}catch (Exception e) {}

System.out.println("Thread 2: waiting to get passenger1 ");

synchronized (passenger1) {

System.out.println("Thread 2: locked passenger1");
}
}
}
};
}
}

Answer

The warning is self explanatory. You define a variable t1 but you don't use it anywhere. If you don't use it, nothing will happen.

my program won't start when I click the Run

Most likely what you intended was to start the thread, rather than just create an object.

Thread t1 = new Thread .... // creates a Thread object.
t1.start(); // actually starts the thread.