0%

多线程——不安全案例

不安全的买票

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
package com.sympa.lesson01;

//线程不安全,有负数
public class Tickets01 implements Runnable{

private int ticket = 10;
@Override
public void run() {
while(true) {
if (ticket <= 0) break;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//Thread.currentThread() 获得当前线程对象的引用
System.out.println(Thread.currentThread().getName() + "拿到了第" + ticket-- + "张票");
}
}

public static void main(String[] args){
Tickets01 tickets01 = new Tickets01();
new Thread(tickets01, "黄牛1号").start();
new Thread(tickets01, "黄牛2号").start();
new Thread(tickets01, "黄牛3号").start();
}
}
------ THEEND ------

欢迎关注我的其它发布渠道