File size: 789 Bytes
0284885
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package Thread_safe_package;

public class MyRunnable implements Runnable {

    static int ticket = 0;

    @Override
    public void run() {
        //1、循环
        while (true) {
            //2、同步代码块(同步方法)
            if (method()) break;
        }

    }

    private synchronized boolean method() {
        //3、判断共享数据是否到了末尾
        if (ticket == 100) {
            return true;
        } else {
            try {
                Thread.sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            ticket++;
            System.out.println(Thread.currentThread().getName() +
                    "在卖第" + ticket + "张票");
        }
        return false;

    }
}