1 package multithread.test;
2
3
4
5 /*
6 * 静态的同步函数使用的锁是: 该函数所属字节码文件对象
7 * 可以用getClass方法获取,也可以用当前 类名.class 表示
8 *
9 *
10 */
11 class Ticket implements Runnable {//extends Thread {
12 private static int num = 100;//静态是可以的,根据实际看,有可能是这个线程负责这种100张,另一个线程时另一种票100张
13 Object obj = new Object();
14 boolean flag = true;
15 public void run() /*throws 不处理就抛,但是实现接口覆盖的方法,接口没有声明过异常,只能catch不能声明*/{
16 // Object obj = new Object();//每个线程开启都会创建一个对象,就会有不同锁,会出错
17 System.out.println("this:"+this);
18 if (flag) {
19 while(true) {
20 synchronized (this.getClass()) {//验证和静态同步函数的锁是否一致
21 if (num>0) {
22 try {
23 Thread.sleep(10);//sleep方法有个抛出
24 } catch (InterruptedException e) {
25 }
26 //
27 System.out.println(Thread.currentThread().getName()+"....sale...."+ num--);
28 }
29 }
30
31 }
32 }else {
33 while(true) {
34 this.show();
35 }
36 }
37
38 }
39 public static synchronized void show() {//同步函数加静态的锁是字节码文件对象(用的getClass方式获取),不是this,java特点是对字节码文件进内存先封装成对象
40 if (num>0) {
41 try {
42 Thread.sleep(10);//sleep方法有个抛出
43 } catch (InterruptedException e) {
44 }
45 //
46 System.out.println(Thread.currentThread().getName()+"....function...."+ num--);
47 }
48 }
49 }
50 //会出现两个相同的票数,可能会出现0票,因为用了不同的锁,同步函数的锁和代码块的锁不一样,同步函数仅仅是函数代表了同步性,本身不带锁,
51 public class StaticSynFunctionDemo {
52
53 public static void main(String[] args) {
54 // TODO Auto-generated method stub
55 Ticket t = new Ticket();//创建一个线程任务对象。
56
57 // Class clazz = t.getClass(); 两种获取class文件对象方式
58 // Class clazz = Ticket.class;
59 // System.out.println("t:"+t.getClass());
60 Thread t1 = new Thread(t);
61 Thread t2 = new Thread(t);
62 // Thread t3 = new Thread(t);
63 // Thread t4 = new Thread(t);
64
65 t1.start();
66 try {
67 Thread.sleep(10);
68 } catch (InterruptedException e) {
69
70 }
71 t.flag = false;
72 t2.start();
73 // t3.start();
74 // t4.start();
75 }
76
77 }