日期:2014-05-20 浏览次数:20814 次
class ThreadSale implements Runnable{ //创建Runnable接口类
private int tickets = 10; //私有变量tickets 代表机票数,是共享数据
public void run(){
while(true){
if(tickets > 0)
System.out.println(Thread.currentThread().getName() + "售机票第"+tickets+"号");
else
System.exit(0);
}
}
}
public class RunnableShare{ //在主类里创建并启动3个线程对象
public static void main(String[] args){
ThreadSale t = new ThreadSale(); //用此对象t作为参数创建3个线程 第二个对象是线程名
Thread t1 = new Thread(t,"第1售票窗口");
Thread t2 = new Thread(t,"第2售票窗口");
Thread t3 = new Thread(t,"第3售票窗口");
t1.start();
t2.start();
t3.start();
}
}
System.out.println(Thread.currentThread().getName() + "售机票第"+tickets+"号");
System.out.println(Thread.currentThread().getName() + "售机票第"+(tickets--)+"号");