public class Runabletest implements Runnable{
private int num = 5;
public void run(){
for (int i = 0; i < 10; i++) { //多执行几次,可以比较清楚的查看3个线程
if(num>0) //如果不限制会出现负票产生
System.out.println(Thread.currentThread().getName()+"正在出售票"+num--);
else
System.out.println("票已售完"); //为查看线程的运行
}
}
public static void main(String[] args) {
Runabletest rt = new Runabletest();
Thread thr1 = new Thread(rt);
Thread thr2 = new Thread(rt);
Thread thr3 = new Thread(rt);
thr1.start();
thr2.start();
thr3.start();
}
}
创建了一个Runabletest对象,让num是thr1/thr2/thr3三个只操作一个num资源,详细参考http://www.cnblogs.com/xt0810/p/3558000.html