本帖最后由 鲍阳 于 2015-3-6 00:31 编辑
这个是毕老师视频里的例子,day11里的DeadLockDemo.java。有两个疑问:
1.为什么要加try{Thread.sleep(5);}catch(Exception e){}这行呢,不加这行好像就不容易出死锁问题了
2.如果把Ticket t=new Ticket();Thread t1=new Thread(t);Thread t2=new Thread(t);这三行换成后面这俩就不会死锁了,(Thread t1=new Thread(new Ticket(true));Thread t2=new Thread(new Ticket(false))),是不是因为后面是new了两不同的Ticket对象,所以t1、t2的同步函数用的this锁不是同一个了
- class Ticket implements Runnable
- {
- private int tick=100000;
- boolean flag=true;
- Object obj=new Object();
- Ticket(){}
- Ticket(boolean flag){
- this.flag=flag;
- }
- public void run()
- {
- if (flag)
- {
-
- while (true)
- {
- synchronized(obj){
- show();
- }
- }
- }
- else
- while (true)
- {
- //synchronized(obj)
-
- show();
-
-
- }
- }
- public synchronized void show()
- {
- synchronized(obj){
-
- if (tick>0)
- {
- try{Thread.sleep(15);}catch(Exception e){}
- System.out.println(Thread.currentThread().getName()+"..."+tick--+"张票...");
- }
- }
- }
- }
- class DeadLockDemo
- {
- public static void main(String[] args)
- {
- Ticket t=new Ticket();
- Thread t1=new Thread(t);
- Thread t2=new Thread(t);
- //Thread t1=new Thread(new Ticket(true));
- //Thread t2=new Thread(new Ticket(false));
- t1.start();
- //try{Thread.sleep(5);}catch(Exception e){}
- t.flag=false;
- t2.start();
-
- }
- }
复制代码
|
|