黑马程序员技术交流社区
标题:
多线程
[打印本页]
作者:
18201432758s
时间:
2015-9-21 21:06
标题:
多线程
import java.util.concurrent.locks .*;
class Goods {
String name ; //成员属性
int count = 1;
boolean flag ; // 标记,当成员属性被赋值前是false 赋值后为true
Lock lock = new ReentrantLock(); //创建锁
Condition a = lock.newCondition(); //创建Condtion
Condition b = lock.newCondition();
public void set(String name)throws InterruptedException{
lock.lock(); //线程枷锁同步
try {
while (true) { // 循环判断标记
while (flag){
a.await(); //赋值一次都就让线程等待。
}
this.name = name ; //g给成员变量 赋值,
System.out.println("name="+name+"num="+count+++"xiancheng="+Thread.currentThread().getName());//赋值过后马上打印一次
flag = true ; //改变标记
b.signal(); //叫醒Outport线程
}
}finally{
lock.unlock(); // 将锁释放
}
}
public void out()throws InterruptedException{
lock.lock();
try {
while (true) {
while (!flag) {
b.await();
}
System.out.println("name="+name+"num="+count+"-----------xiangcheng="+Thread.currentThread().getName());
flag = false ;
a.signal();
}
}finally{
lock.unlock();
}
}
}
class Inport implements Runnable {
Goods a ;
Inport(Goods a ){
this.a = a ;
}
public void run(){
try {
a.set("商品");
}
catch (InterruptedException e) {
}
}
}
class Outport implements Runnable{
Goods a ;
Outport(Goods a){
this.a = a ;
}
public void run(){
try {
a.out();
}
catch (InterruptedException e) {
}
}
}
class ShengChanDemo {
public static void main(String[] args) {
Goods a = new Goods();
Inport b = new Inport(a);
Outport c = new Outport(a);
Thread d = new Thread(b);
Thread e = new Thread(b);
Thread f = new Thread(c);
Thread g = new Thread(c);
d.start();
f.start();
e.start();
g.start();
}
}
感觉线程拿到锁之后await了,那么锁还没释放了啊,应该会在while循环中一直跑啊,程序应该跑不起来啊,但是能运行起来怎么回事啊
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/)
黑马程序员IT技术论坛 X3.2