java火车站站_java火车站卖票程序(线程等待)

package com.java.thread.synch;

/**

* 卖票演示

* @author Administrator

* 两个车站卖100张票

*/

public class SellTicket {

static Object obj=new Object();

static int Count=100;

public static void main(String[] args){

//StationOne one =new StationOne(obj);

//StationTwo two =new StationTwo(obj);

//Thread th1=new Thread(one);

//Thread th2=new Thread(two);

//th1.start();

//th2.start();

Thread th1=new Thread(new A());

Thread th2=new Thread(new A());

th1.setName("车站一");

th2.setName("车站二");

th1.start();

th2.start();

}

}

class A implements Runnable{

//String obj=new String("aa");

@SuppressWarnings("static-access")

public void run(){

String obj="aaa";//不能是String obj=new String("aa");aa存放在堆区

//有两个obj,但是它们都是指向同一个aaa,aaa存放在数据区 ,数据区只有一份拷贝

while(true){

synchronized (obj) {

if(SellTicket.Count>0){

try {

Thread.currentThread().sleep(30);

} catch (InterruptedException e) {

//TODO Auto-generated catch block

e.printStackTrace();

}

//System.out.printf("%s卖出了第%d张票\n",Thread.currentThread().getName(),SellTicket.Count);

System.out.println(Thread.currentThread().getName()+SellTicket.Count);

SellTicket.Count--;

}else{

break;

}

}

}

}

}

/**

* 车站一

* @author Administrator

*

*/

class StationOne implements Runnable{

private Object obj;

public StationOne(Object obj){

this.obj=obj;

}

@SuppressWarnings("static-access")

public void run() {

synchronized(obj){

while(SellTicket.Count>0){

obj.notify();

try {

Thread.currentThread().sleep(60);

} catch (InterruptedException e1) {

e1.printStackTrace();

}

System.out.printf("\t\t\t\t车站一卖出了第%d张票\n",SellTicket.Count);

SellTicket.Count--;

try {

obj.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

obj.notify();

}

}

}

/**

* 车站二

* @author Administrator

*

*/

class StationTwo implements Runnable{

private Object obj;

public StationTwo(Object obj){

this.obj=obj;

}

@SuppressWarnings("static-access")

public void run() {

synchronized(obj){

while(SellTicket.Count>0){

obj.notify();

try {

Thread.currentThread().sleep(60);

} catch (InterruptedException e1) {

e1.printStackTrace();

}

System.out.printf("车站二卖出了第%d张票\n",SellTicket.Count);

SellTicket.Count--;

try {

obj.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

obj.notify();

}

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值