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

Java多线程安全

时间:2015-04-10 01:23:09      阅读:170      评论:0      收藏:0      [点我收藏+]

标签:java thread 同步   多线程   java   java多线程安全   

package SwingExample;

public class MultiThreadSafe implements Runnable{
	private int nTicketCount = 10;		// 剩余火车票数量
	private String strPurchaserName;	// 购票人姓名
	
	public static void main(String[] args) {
		// TODO Auto-generated method stub
		MultiThreadSafe t = new MultiThreadSafe("man");
		t.buyTickets();
	}
	
	public void buyTickets() {
		// 假定最多支持5个人同时购票
		MultiThreadSafe man1 = new MultiThreadSafe("man1");
		MultiThreadSafe man2 = new MultiThreadSafe("man2");
		MultiThreadSafe man3 = new MultiThreadSafe("man3");
		MultiThreadSafe man4 = new MultiThreadSafe("man4");
		MultiThreadSafe man5 = new MultiThreadSafe("man5");
		
		Thread t1 = new Thread(man1);
		Thread t2 = new Thread(man2);
		Thread t3 = new Thread(man3);
		Thread t4 = new Thread(man4);
		Thread t5 = new Thread(man5);
		
		t1.start();
		t2.start();
		t3.start();
		t4.start();
		t5.start();
	}
	
	public MultiThreadSafe(String strPurchaserName) {
		// TODO Auto-generated constructor stub
		this.strPurchaserName = strPurchaserName;
	}

	@Override
	public void run() {
		// TODO Auto-generated method stub
		while (nTicketCount > 0) {
			synchronized("") {		// 多线程同步
				nTicketCount--;
				if (nTicketCount == 0) {
					System.out.println(this.strPurchaserName + "前来购票,但票已售完!");
				}
				else if (nTicketCount > 0) {
					System.out.println(this.strPurchaserName + "前来购票,当前余票:" + nTicketCount);
				}
				else {
					System.out.println("余票管理系统异常,请联系系统管理员。");
				}
			}
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}

}

Java多线程安全

标签:java thread 同步   多线程   java   java多线程安全   

原文地址:http://blog.csdn.net/ccpw_cn/article/details/44968245

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