初识并发问题
package com.xiancheng.demo;
// 多个对象同时操作同一个对象
// 买火车票的例子
public class TestThread4 implements Runnable {
// 票数
private int tickets = 10;
@Override
public void run() {
while (true){
if (tickets <= 0){
break;
}
// 模拟延时
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 获取当前执行线程的名字 Thread.currentThread().getName()
System.out.println(Thread.currentThread().getName() + "抢到了第" + tickets-- + "张车票");
}
}
public static void main(String[] args) {
TestThread4 thread4 = new TestThread4();
new Thread(thread4,"小米").start();
new Thread(thread4,"小李").start();
new Thread(thread4,"黄牛").start();
}
}