同步问题的引出
public class Test extends Object {
public static void main(String[] args) throws Exception {
Runnable myThread = new MyThread();
Thread thread0 = new Thread(myThread);
Thread thread1 = new Thread(myThread);
Thread thread2 = new Thread(myThread);
Thread thread3 = new Thread(myThread);
Thread thread4 = new Thread(myThread);
thread0.start();
thread1.start();
thread2.start();
thread3.start();
thread4.start();
}
}
//线程操作类
class MyThread implements Runnable {
private int ticket = 5;
@Override
public void run() {
for (int i = 0; i < 50; i++) {
if (this.ticket > 0) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.ticket--;
System.out.println(Thread.currentThread().getName() + "余票:" + this.ticket);
}
}
}
}
结果截图