1.1抢票系统(多人抢票)
package Demo8;
//多个线程同时操作一个对象
//买车票例子
public class TestThread4 implements Runnable {
private int ticket_nums=10;
@Override
//重写run()
public void run() {
while (true){
if(ticket_nums<=0){
break;
}
//thread中有个延迟模拟sleep,否则第一个人网速很快,全部抢完
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"拿到了第"+ticket_nums--+"票");
}
}
public static void main(String[] args) {
TestThread4 testThread4 = new TestThread4();
String name;
//调用start()方法
new Thread( testThread4,name="小明").start();
new Thread(testThread4,name="老师").start();
new Thread(testThread4,name="黄牛").start();
}
}
结果:
1.2问题:两个人抢到同一张票(并发问题),即多线程操作同一个资源,线程不安全,数据紊乱