package test.access.foreign; public class Foreign { public static void main(String args[]){ MyThread mt=new MyThread(); for(int i=0;i<20;i++)//模拟20个售票终端 new Thread(mt).start(); } /** * 打印结果: */ } class MyThread implements Runnable{ int tacket=5; @Override public void run() { try { sale(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } private synchronized void sale() throws InterruptedException{ long time=(long) (Math.random()*5000); System.out.println("线程"+Thread.currentThread().getName()+"休眠"+time+"毫秒"); Thread.sleep(time);//模拟网络延时 if(tacket>=1){ System.out.println("售票:"+tacket--); }else{ System.out.println("没票啦"); } } }
方式二:
package test.access.foreign; public class Foreign { public static void main(String args[]){ MyThread mt=new MyThread(); for(int i=0;i<20;i++)//模拟20个售票终端 new Thread(mt).start(); } /** * 打印结果: */ } class MyThread implements Runnable{ int tacket=5; @Override public void run() { try { synchronized(this){ long time=(long) (Math.random()*5000); System.out.println("线程"+Thread.currentThread().getName()+"休眠"+time+"毫秒"); Thread.sleep(time);//模拟网络延时 if(tacket>=1){ System.out.println("售票:"+tacket--); }else{ System.out.println("没票啦"); } } } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }