日期:2014-05-20 浏览次数:20655 次
package zhangming.csdn;
class MyThread implements Runnable
{
private int ticket=10;
public void run()
{
for(int i=0;i<10;i++) //建议不要将i的最大值设的太大这样太浪费资源
{
//先睡眠,后锁定,以便让其他线程进来
try
{
Thread.sleep(1000);
}catch(InterruptedException e){e.printStackTrace();}
//在进行售票时,需要进行锁定
synchronized(this)
{
if(ticket>0)
{
System.out.println(Thread.currentThread().getName()+"卖掉第"+ticket--+"张票");
}
}
}
}
}
public class SynchronizedDemo
{
public static void main(String args[])
{
MyThread mt=new MyThread();
Thread t1=new Thread(mt,"窗口1");
Thread t2=new Thread(mt,"窗口2");
Thread t3=new Thread(mt,"窗口3");
t1.start();
t2.start();
t3.start();
}
}
class MyThread implements Runnable {
private int ticket = 10;
public void run() {
while (ticket > 0) {//循环条件