您的位置:首页 > 编程语言 > Java开发

java线程同步(生产者消费者应用-模拟叫号系统)

2015-10-15 16:49 621 查看
执行结果:

顾客取得:票据0

票据0:顾客请到窗口11

顾客取得:票据1

票据1:顾客请到窗口10

顾客取得:票据2

票据2:顾客请到窗口11

顾客取得:票据3

票据3:顾客请到窗口10

顾客取得:票据4

票据4:顾客请到窗口11

顾客取得:票据5

票据5:顾客请到窗口10

顾客取得:票据6

票据6:顾客请到窗口11

顾客取得:票据7

票据7:顾客请到窗口10

票据类-写法一:



public class Titckets {

Stack<Integer> tickets = new Stack<Integer>();

public synchronized void getTicket() {

while (tickets.size() ==0) {//用while不用if保证遇到异常时仍能连续验证是不是为空

try {

this.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

notifyAll();//先唤醒其他等待本对象锁的线程,然后自己再让出对象锁,唤醒其他线程语句执行后当前线程不会立即结束,直到同步块代码执行完才让出对象锁

System.out.println("票据" + tickets.pop() + ":顾客请到窗口"

+ Thread.currentThread().getId());

}

public synchronized void setTicket(int i) {

while (tickets.size()==10) {//如果等待人数超过10则停止出号,//用while不用if保证遇到异常时仍能连续验证是不是已满

try {

this.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

notifyAll();//先唤醒其他等待本对象锁的线程,然后自己再让出对象锁

tickets.push(i);

System.out.println("顾客取得:票据" + i);

}

}



票据类-写法二:

public class Titckets {

Stack<Integer> tickets = new Stack<Integer>();

public synchronized void getTicket() {

if (tickets.size() > 0) {

System.out.println("票据" + tickets.pop() + ":顾客请到窗口"

+ Thread.currentThread().getId());

}

notifyAll();//先唤醒其他等待本对象锁的线程,然后自己再让出对象锁

try {

this.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

public synchronized void setTicket(int i) {

if (tickets.size() < 10) {//如果等待人数超过10则停止出号

tickets.push(i);

System.out.println("顾客取得:票据" + i);

}

notifyAll();//先唤醒其他等待本对象锁的线程,然后自己再让出对象锁

try {

this.wait();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

取号线程类:

public class Producer implements Runnable {

private Titckets titckets;

public void run() {

for (int j = 0; j < 100; j++) {

titckets.setTicket(j);

}

}

public Producer(Titckets t) {

titckets = t;

}

}

服务窗口类:

public class Custome implements Runnable {

private Titckets titckets;

public void run() {

for (int j = 0; j < 1000; j++) {

titckets.getTicket();

}

}

public Custome(Titckets t) {

titckets = t;

}

}

主线程:

public class GetAndSet {

public static void main(String[] args) {

Titckets t = new Titckets();

new Thread(new Producer(t)).start();// 叫号线程

new Thread(new Custome(t)).start();// 窗口1服务线程

new Thread(new Custome(t)).start();// 窗口2服务线程

new Thread(new Custome(t)).start();// 窗口3服务线程

}

}

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: