码迷,mamicode.com
首页 > 编程语言 > 详细

线程同步两种方式

时间:2014-11-10 13:51:51      阅读:217      评论:0      收藏:0      [点我收藏+]

标签:线程   thread   网络   终端   java   

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();
		}		
	}
}

线程同步两种方式

标签:线程   thread   网络   终端   java   

原文地址:http://blog.csdn.net/ztt_1119/article/details/40979343

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!