public class Pro_Con_ticket {
public static void main(String[] args) {
//进程间通信
Tickets t =new Tickets(10);
new Producer(t).start();
new Consumer(t).start();
}
}
//多线程同步控制
class Tickets{
int size;
int number=0;
boolean available = false;
public Tickets(int size){
this.size = size;
}
//方法互斥
public synchronized void put(){
//如果还有存票代售,则存票线程等待
if(available)
try{
wait();
}catch(Exception e){}
System.out.println("Producer puts tickets " + (++ number));
available = true;
//存票后唤醒售票线程开始售票
notify();
}
public synchronized void sell(){
//如果没有存票,则售票线程等待
if(!available)
try{
wait();
}catch(Exception e){}
System.out.println("Consumer buys tickets " + number);
available = false;
//售票后唤醒存票线程开始存票
notify();
if(number ==size)
number = size +1;
}
}
class Producer extends Thread{
Tickets t = null;
public Producer(Tickets t){
this.t =t;
}
public void run(){
while(t.number<t.size)
t.put();
}
}
class Consumer extends Thread{
Tickets t =null;
public Consumer(Tickets t){
this.t =t;
}
public void run(){
while(t.number<=t.size)
t.sell();
}
}
本文深入探讨了并发控制与多线程同步技术的实现,通过实例展示了如何利用Java语言实现进程间通信,包括生产者-消费者模式、互斥与通知机制的应用,以确保线程安全与高效数据交互。

被折叠的 条评论
为什么被折叠?



