线程同步两种方式

来源:互联网 发布:win10极速系统优化 编辑:程序博客网 时间:2024/04/30 03:14
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;@Overridepublic void run() {try {sale();} catch (InterruptedException e) {// TODO Auto-generated catch blocke.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;@Overridepublic 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 blocke.printStackTrace();}}}

0 0
原创粉丝点击