1 package multithread3;
2
3
4
5 /*
6 * 死锁:常见情景之一:同步的嵌套。
7 * 面试可能会让写死锁
8 */
9 class Ticket implements Runnable {
10 private /*static*/ int num = 200;
11 Object obj = new Object();
12 boolean flag = true;
13 public void run() {
14
15 // System.out.println("this:"+this);
16 if (flag) {
17 while(true) {
18 synchronized (obj) {
19 show();
20 }
21 }
22
23
24 }else {
25 while(true) {
26 this.show();
27 }
28 }
29 }
30
31
32 public synchronized void show() {
33
34 synchronized (obj) {
35 if (num>0) {
36 try {
37 Thread.sleep(10);//sleep方法有个抛出
38 } catch (InterruptedException e) {
39 }
40 //
41 System.out.println(Thread.currentThread().getName()+"....function...."+ num--);
42 }
43 }
44
45 }
46 }
47
48 //会出现两个相同的票数,可能会出现0票,因为用了不同的锁,同步函数的锁和代码块的锁不一样,同步函数仅仅是函数代表了同步性,本身不带锁,
49 public class DeadLockDemo {
50
51 public static void main(String[] args) {
52 // TODO Auto-generated method stub
53 Ticket t = new Ticket();//创建一个线程任务对象。
54
55
56 System.out.println("t:"+t);
57 Thread t1 = new Thread(t);
58 Thread t2 = new Thread(t);
59 // Thread t3 = new Thread(t);
60 // Thread t4 = new Thread(t);
61
62 t1.start();
63 try {
64 Thread.sleep(10);
65 } catch (InterruptedException e) {
66
67 }
68 t.flag = false;
69 t2.start();
70 // t3.start();
71 // t4.start();
72 }
73
74 }