线程的同步:采用同步代码块实现同步

/*采用同步代码块实现同步*/
class MyThread11 implements Runnable {
private int ticket = 80;
public void run(){
for(int i=0; i<100; i++){
synchronized(this){
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 SynchronizedDemo {


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

}


}

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