package org.chen.sync;
class MyThread01 implements Runnable{
private int ticket = 5;
public void run(){
for(int i = 0;i<100;i++){
synchronized(this){
if(ticket>0){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
System.out.println("买票:ticket = "+ticket--);
}
}
}
}
}
public class SyncDemo02 {
public static void main(String[] args) {
MyThread01 my = new MyThread01();
Thread t1 = new Thread(my);
Thread t2 = new Thread(my);
Thread t3 = new Thread(my);
t1.start();
t2.start();
t3.start();
}
}
class MyThread01 implements Runnable{
private int ticket = 5;
public void run(){
for(int i = 0;i<100;i++){
synchronized(this){
if(ticket>0){
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
}
System.out.println("买票:ticket = "+ticket--);
}
}
}
}
}
public class SyncDemo02 {
public static void main(String[] args) {
MyThread01 my = new MyThread01();
Thread t1 = new Thread(my);
Thread t2 = new Thread(my);
Thread t3 = new Thread(my);
t1.start();
t2.start();
t3.start();
}
}