标签:
1 package com.java.thread.synch; 2 3 /** 4 * 卖票演示 5 * @author Administrator 6 * 两个车站卖100张票 7 */ 8 public class SellTicket { 9 static Object obj=new Object(); 10 static int Count=100; 11 public static void main(String[] args){ 12 // StationOne one =new StationOne(obj); 13 // StationTwo two =new StationTwo(obj); 14 // Thread th1=new Thread(one); 15 // Thread th2=new Thread(two); 16 // th1.start(); 17 // th2.start(); 18 19 Thread th1=new Thread(new A()); 20 Thread th2=new Thread(new A()); 21 th1.setName("车站一"); 22 th2.setName("车站二"); 23 th1.start(); 24 th2.start(); 25 } 26 } 27 28 class A implements Runnable{ 29 // String obj=new String("aa"); 30 @SuppressWarnings("static-access") 31 public void run(){ 32 String obj="aaa";//不能是String obj=new String("aa");aa存放在堆区 33 // 有两个obj,但是它们都是指向同一个aaa,aaa存放在数据区 ,数据区只有一份拷贝 34 while(true){ 35 synchronized (obj) { 36 if(SellTicket.Count>0){ 37 try { 38 Thread.currentThread().sleep(30); 39 } catch (InterruptedException e) { 40 // TODO Auto-generated catch block 41 e.printStackTrace(); 42 } 43 // System.out.printf("%s卖出了第%d张票\n",Thread.currentThread().getName(),SellTicket.Count); 44 System.out.println(Thread.currentThread().getName()+SellTicket.Count); 45 SellTicket.Count--; 46 }else{ 47 break; 48 } 49 } 50 51 } 52 } 53 } 54 55 56 /** 57 * 车站一 58 * @author Administrator 59 * 60 */ 61 class StationOne implements Runnable{ 62 private Object obj; 63 public StationOne(Object obj){ 64 this.obj=obj; 65 } 66 @SuppressWarnings("static-access") 67 public void run() { 68 synchronized(obj){ 69 while(SellTicket.Count>0){ 70 obj.notify(); 71 try { 72 Thread.currentThread().sleep(60); 73 } catch (InterruptedException e1) { 74 e1.printStackTrace(); 75 } 76 System.out.printf("\t\t\t\t车站一卖出了第%d张票\n",SellTicket.Count); 77 SellTicket.Count--; 78 try { 79 obj.wait(); 80 } catch (InterruptedException e) { 81 e.printStackTrace(); 82 } 83 } 84 obj.notify(); 85 } 86 } 87 } 88 89 /** 90 * 车站二 91 * @author Administrator 92 * 93 */ 94 class StationTwo implements Runnable{ 95 private Object obj; 96 public StationTwo(Object obj){ 97 this.obj=obj; 98 } 99 @SuppressWarnings("static-access") 100 public void run() { 101 synchronized(obj){ 102 while(SellTicket.Count>0){ 103 obj.notify(); 104 try { 105 Thread.currentThread().sleep(60); 106 } catch (InterruptedException e1) { 107 e1.printStackTrace(); 108 } 109 System.out.printf("车站二卖出了第%d张票\n",SellTicket.Count); 110 SellTicket.Count--; 111 try { 112 obj.wait(); 113 } catch (InterruptedException e) { 114 e.printStackTrace(); 115 } 116 } 117 obj.notify(); 118 } 119 } 120 }
标签:
原文地址:http://www.cnblogs.com/w731478725/p/4175202.html