死锁例子:
public class Demo{
public static Printer printer=new Printer();
public static Scan scan=new Scan();
public static void main(String arg[]) throws Exception {
new Thread(new Worker_A()).start();
new Thread(new Worker_B()).start();
// Thread t1=new Thread(new Worker_A());
// t1.start();
// Thread t2=new Thread(new Worker_B());
// t2.start();
}
}
class Printer{
}
class Scan{
}
class Worker_A implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
synchronized(Demo.printer){
System.out.println("A在使用打印机"+Demo.printer);
try {
Thread.sleep(3000);
synchronized(Demo.scan) {
System.out.println("A正在使用扫描仪"+Demo.scan);
Thread.sleep(2000);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class Worker_B implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
synchronized(Demo.scan){
System.out.println("B正在使用扫描仪"+Demo.scan);
try {
Thread.sleep(3000);
synchronized(Demo.printer) {
System.out.println("B在使用打印机"+Demo.printer);
Thread.sleep(2000);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}