黑马程序员技术交流社区
标题:
谁能给个多线程典型的例子
[打印本页]
作者:
提菩--空
时间:
2014-6-8 23:09
标题:
谁能给个多线程典型的例子
谁能给个多线程典型的例子,我自己也从网上搜了一些,但感觉不具有代表性
作者:
ender
时间:
2014-6-8 23:26
本帖最后由 ender 于 2014-6-8 23:28 编辑
经典的生产者和消费者模型 用的Lock接口加的锁
class StorageLock {
int count;
String product;
boolean flag;
Lock lock = new ReentrantLock();
Condition con = lock.newCondition();
Condition pro = lock.newCondition();
public void produce(String product){
lock.lock();
try{
while(flag)
pro.await();
this.product=product;
count++;
System.out.println(product+"...Producer..."+count);
flag=true;
con.signal();
}
catch(InterruptedException e){}
finally{
lock.unlock();
}
}
public void consume(){
lock.lock();
try{
while(!flag)
con.await();
System.out.println(product+"...Consumer......."+count);
flag=false;
pro.signal();
}
catch(InterruptedException e){}
finally{
lock.unlock();
}
}
}
class ProducerLock implements Runnable{
StorageLock sto;
ProducerLock(StorageLock sto){
this.sto=sto;
}
public void run(){
while(true)
sto.produce("commodity");
}
}
class ConsumerLock implements Runnable{
StorageLock sto;
ConsumerLock(StorageLock sto){
this.sto=sto;
}
public void run(){
while(true)
sto.consume();
}
}
class ProducerConsumerLock{
public static void main(String[] args){
StorageLock sto = new StorageLock();
new Thread(new ProducerLock(sto)).start();
new Thread(new ProducerLock(sto)).start();
new Thread(new ConsumerLock(sto)).start();
new Thread(new ConsumerLock(sto)).start();
}
}
复制代码
作者:
提菩--空
时间:
2014-6-8 23:27
ender 发表于 2014-6-8 23:26
经典的生产者和消费者模型 用的Lock接口加的锁
谢谢分享
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2