死锁就是共享资源被占用,线程会一直等待,或者是两个线程相互想使用对方的资源,在没有得到对方资源情况下,又不释放自己的资源,这时两个线程都不往下走,也会造成死锁。- public class Test {
- public static void main(String[] args) {
- A a1 = new A();
- A a2 = new A();
- Thread t1 = new Thread1(a1, a2);
- Thread t2 = new Thread1(a2, a1);
- t1.start();
- t2.start();
- }
- }
- class Thread1 extends Thread {
- private A from;
- private A to;
-
- public Thread1(A from, A to) {
- this.from = from;
- this.to = to;
- }
- public void run() {
- from.fun1(to);
- }
- }
- class A {
- public synchronized void fun1(A a) {
- System.out.println(Thread.currentThread().getName() + ": fun1()...");
- try {
- Thread.sleep(1000);
- } catch(InterruptedException e) {}
- a.fun2();
- }
- public synchronized void fun2() {}
- }
复制代码 |