On souhaite créer deux threads qui change les coordonées d'un même point
public class Point { private int x; private int y; public void move(int x,int y) { this.x=x; this.y=y; } @Override public String toString() { return "("+x+','+y+')'; } public static void main(String[] args) { final Point p=new Point(); for(int i=0;i<2;i++) { final int id=i; new Thread(new Runnable() { public void run() { for(;;) { p.move(id,id); System.out.println(p); } } }).start(); } } }
Voici un code simplifié d'un code fournit par un étudiant :
public class Oups { private int value; public void setValue(int value) { synchronized(readLock) { synchronized(writeLock) { this.value=value; } } } public int getValue() { synchronized(readLock) { return value; } } public void performs() throws InterruptedException { Thread t=new Thread() { @Override public void run() { setValue(12); } }; synchronized(writeLock) { t.start(); Thread.sleep(1000); System.out.println(getValue()); } } private final Object readLock=new Object(); private final Object writeLock=new Object(); public static void main(String[] args) throws InterruptedException { Oups oups=new Oups(); test.performs(); } }
Où se situe l'interblocage dans le code ci-dessous :
public class FunnyDeadLock { static synchronized void m() { System.out.println("hello"); } static { Thread t=new Thread() { @Override public synchronized void run() { m(); } }; t.start(); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } synchronized(t) { System.out.println("hello 2"); } } }