程序员人生 网站导航

Java多线程安全

栏目:php教程时间:2015-04-20 07:58:31
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(); } } } }

------分隔线----------------------------
------分隔线----------------------------

最新技术推荐