1、实现Runnable接口可以资源共享(卖票系统)
class MyThread implements Runnable{
private int ticket=5;
public void run(){
for(int i=0;i<100;i++){
this.sale();
}
}
public synchronized void sale(){
if(ticket>=0){
try{
Thread.sleep(600);
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println(ticket--);
}
}
};
public class Synchronidemo{
public static void main(String[] args){
MyThread mt=new MyThread();
Thread t1=new Thread(mt);
Thread t2=new Thread(mt);
Thread t3=new Thread(mt);
t1.start();
t2.start();
t3.start();
}
}
程序输出结果:
5
4
3
2
1
0