- package com.itheima.day11;
- /*
- 死锁。
- 同步中嵌套同步。
- 死锁是这样一种情形:多个线程同时被阻塞,它们中的一个或者全部都在等待某个资源被释放。由于线程被无限期地阻塞,因此程序不可能正常终止。
- 导致死锁的根源在于不适当地运用“synchronized”关键词来管理线程对特定对象的访问。“synchronized”关键词的作用是,
- 确保在某个时刻只有一个线程被允许执行特定的代码块,因此,
- 被允许执行的线程首先必须拥有对变量或对象的排他性的访问权。
- 当线程访问对象时,线程会给对象加锁,而这个锁导致其它也想访问同一对象的线程被阻塞,直至第一个线程释放它加在对象上的锁。
- */
- class Ticket implements Runnable
- {
- private int tick = 1000;
- Object obj = new Object();
- boolean flag = true;
- public void run()
- {
- if(flag)
- {
- while(true)
- {
- synchronized(obj)
- {
- show();
- }
- }
- }
- else
- while(true)
- show();
- }
- public synchronized void show()//this
- {
- synchronized(obj)
- {
- if(tick>0)
- {
- try{Thread.sleep(10);}catch(Exception e){}
- System.out.println(Thread.currentThread().getName()+"....code : "+ tick--);
- }
- }
- }
- }
- class DeadLockDemo
- {
- public static void main(String[] args)
- {
- Ticket t = new Ticket();
- Thread t1 = new Thread(t);
- Thread t2 = new Thread(t);
- t1.start();
- try{Thread.sleep(10);}catch(Exception e){}
- t.flag = false;
- t2.start();
- }
- }
复制代码 Thread-0....code : 980
Thread-0....code : 979
Thread-0....code : 978
Thread-0....code : 977
Thread-0....code : 976
Thread-0....code : 975
Thread-0....code : 974
Thread-0....code : 973
Thread-0....code : 972
Thread-0....code : 971
Thread-0....code : 970
Thread-0....code : 969
Thread-0....code : 968
Thread-0....code : 967
Thread-0....code : 966
Thread-0....code : 965
Thread-0....code : 964
Thread-0....code : 963
Thread-0....code : 962
Thread-0....code : 961
Thread-0....code : 960
Thread-0....code : 959
Thread-0....code : 958
Thread-0....code : 957
Thread-0....code : 956
Thread-0....code : 955
Thread-0....code : 954
Thread-0....code : 953
Thread-0....code : 952
Thread-0....code : 951
Thread-0....code : 950
Thread-0....code : 949
Thread-0....code : 948
Thread-0....code : 947
Thread-0....code : 946
Thread-0....code : 945
Thread-0....code : 944
Thread-0....code : 943
Thread-0....code : 942
Thread-0....code : 941
Thread-0....code : 940
Thread-1....code : 939
Thread-1....code : 938
Thread-1....code : 937
Thread-1....code : 936
Thread-1....code : 935
Thread-1....code : 934
Thread-1....code : 933
Thread-1....code : 932
Thread-1....code : 931
Thread-1....code : 930
Thread-1....code : 929
Thread-1....code : 928
Thread-1....code : 927
Thread-1....code : 926
Thread-1....code : 925
Thread-1....code : 924
Thread-1....code : 923
Thread-1....code : 922
Thread-1....code : 921
Thread-1....code : 920
Thread-1....code : 919
Thread-1....code : 918
Thread-1....code : 917
Thread-1....code : 916
Thread-1....code : 915
Thread-1....code : 914
在这里阻塞了,为什么
|
|