方法同步:
package threaddemo;
class MyThread implements Runnable{
private int ticket =5;
public void run(){
for(int i=0;i<10;i++)
{
tell();
}
}
public synchronized void tell(){
synchronized(this){
if(ticket>0){
try {
Thread.sleep(200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("车票"+ticket--);
}
}
}
}
public class ThreadDemo {
public static void main(String[] args)
{
MyThread m = new MyThread();
Thread t1 = new Thread(m);
Thread t2 = new Thread(m);
Thread t3 = new Thread(m);
t1.start();
t2.start();
t3.start();
}
}