62,614
社区成员
发帖
与我相关
我的任务
分享
class Test{
public static void main(String[] args) {
WareHouse ware = new WareHouse();
Producer pro = new Producer(ware);
Consumer con = new Consumer(ware);
System.out.println("lds");
pro.start();
con.start();
}
}
class WareHouse{
int number;
public synchronized void put(){
try {
wait();
} catch (Exception e) {
}
}
public synchronized void get(){
try {
notify();
} catch (Exception e) {
}
}
}
class Producer extends Thread{
public Producer(WareHouse proHouse){
}
}
class Consumer extends Thread{
public Consumer(WareHouse conHouse){
}
}
if(number==MAX_SIZE){
this.wait();//如果满了则等待消费者消费
}
number++//不满的情况下继续生产;
this.notifyAll();//如果消费这线程等待中,可以解除它的等待状态
private final int MAX_SIZE;
if(number==MAX_SIZE){
this.wait();//如果满了则等待消费者消费}
number++//不满的情况下继续生产;
this.notifyAll();//如果消费这线程等待中,可以解除它的等待状态
public void run(){
while(true){
WareHouse.put();
Thread.sleep(500);}}
public class TicketTest {
/**
* @param args
*/
public static void main(String[] args) {
TicketStack ts = new TicketStack();
SoldTicket st = new SoldTicket(ts);
BuyTicket bt = new BuyTicket(ts);
new Thread(st).start();
new Thread(bt).start();
}
}
class Ticket {
int num;
public Ticket(int num) {
this.num = num;
}
}
/*存储票的栈*/
class TicketStack {
Ticket[] arrTicket = new Ticket[5];
int index = 0;
public synchronized void push(Ticket ticket) {
while(index == arrTicket.length) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
arrTicket[index] = ticket;
index++;
}
public synchronized Ticket pop() {
while(index == 0) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.notify();
index--;
return arrTicket[index];
}
}
//出票的人
class SoldTicket implements Runnable{
TicketStack ts = null;
public SoldTicket(TicketStack ts) {
this.ts = ts;
}
public void run() {
for(int i = 0;i<10;i++) {
Ticket t = ts.pop();
System.out.println("出票"+t.num);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//买票的人
class BuyTicket implements Runnable{
TicketStack ts = null;
public BuyTicket(TicketStack ts) {
this.ts = ts;
}
public void run() {
for(int i =0;i<10;i++) {
Ticket t = new Ticket(i);
ts.push(t);
System.out.println("买票"+t.num);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}