线程的同步:通过同步方法实现

/*同步的实现:通过同步方法实现*/
class MyThread12 implements Runnable{
private int ticket =50;
public void run(){
for(int i=0; i<80; i++){
this.sale();
}
}
public synchronized void sale(){
if(ticket>0){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"运行"+ticket--);
}
}
}
public class SynchronizedDemo1 {


public static void main(String[] args) {
// TODO Auto-generated method stub
MyThread12 mt = new MyThread12();
new Thread(mt).start();
new Thread(mt).start();
new Thread(mt).start();
}


}

你可能感兴趣的:(线程)