java 多线程的售票问题
java 多线程的售票问题
- 对票的库存进行操作
public class Tickets implements Runnable{
private int ticket = 100;
public void run() {
while (true) {
if ( ticket > 0 ) {
try{
Thread.sleep(10);
}catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" 出售第 "+ticket--);
}
}
}
}
- 开启多个线程同事操作票的库存
public class ThDemo {
public static void main(String[] args) {
Tickets tickets = new Tickets();
Thread t0 = new Thread(tickets);
t0.setName("1hao");
Thread t1 = new Thread(tickets);
t1.setName("2hao");
Thread t2 = new Thread(tickets);
t2.setName("3hao");
t0.start();
t1.start();
t2.start();
}
}
- 结果是库存数减到负数还可以售票, 利用同步代码块解决这个问题
public class Tickets implements Runnable{
private int ticket = 100;
private Object obj = new Object();
public void run() {
while (true) {
synchronized (obj) {
if ( ticket > 0 ) {
try{
Thread.sleep(10);
}catch (Exception e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" 出售第 "+ticket--);
}
}
}
}
}
欢迎各位大虾指正