Featured image of post 【java并发编程】多线程的线程安全问题

【java并发编程】多线程的线程安全问题

多线程编程虽然用起来很爽,同时也会带来一些问题

线程安全问题

看一下下面的代码:

 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
public class ThreadUnsafe {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();
        for (int i = 0; i < 10; i++) {
            Thread thread = new Thread(ticket);
            thread.start();
        }
    }
}

class Ticket implements Runnable {
    private static int ticketNum = 20;

    @Override
    public void run() {
        while (true) {
            if (ticketNum > 0) {
                try {
                    TimeUnit.MILLISECONDS.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(Thread.currentThread().getName() + " sale a ticket,current:" + saleTicket());
            }else {
                System.out.println("票已经卖完了");
                break;
            }
        }
    }

    public int saleTicket(){
        return ticketNum--;
    }
}

执行结果:

 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
36
37
38
39
40
Thread-1 sale a ticket,current:18
Thread-9 sale a ticket,current:11
Thread-3 sale a ticket,current:19
Thread-4 sale a ticket,current:12
Thread-6 sale a ticket,current:14
Thread-8 sale a ticket,current:13
Thread-2 sale a ticket,current:15
Thread-5 sale a ticket,current:20
Thread-0 sale a ticket,current:17
Thread-7 sale a ticket,current:16
Thread-7 sale a ticket,current:10
Thread-9 sale a ticket,current:5
Thread-1 sale a ticket,current:6
Thread-6 sale a ticket,current:7
Thread-3 sale a ticket,current:8
Thread-4 sale a ticket,current:9
Thread-8 sale a ticket,current:9
Thread-2 sale a ticket,current:9
Thread-0 sale a ticket,current:9
Thread-5 sale a ticket,current:9
Thread-4 sale a ticket,current:2
Thread-7 sale a ticket,current:-2
票已经卖完了
Thread-6 sale a ticket,current:-1
票已经卖完了
Thread-1 sale a ticket,current:0
票已经卖完了
Thread-9 sale a ticket,current:0
票已经卖完了
Thread-8 sale a ticket,current:1
票已经卖完了
Thread-3 sale a ticket,current:4
票已经卖完了
Thread-5 sale a ticket,current:1
票已经卖完了
Thread-2 sale a ticket,current:4
票已经卖完了
Thread-0 sale a ticket,current:3
票已经卖完了
票已经卖完了

从执行结果看得出来,存在

TODO