【发布时间】:2018-02-20 06:52:16
【问题描述】:
我是一名 java 初学者,我在学习 java 中的 Thread 时编写了以下代码。我认为,如果我锁定Resource.set() 并注释掉Lock.unlock(),则Resource.out() 中的代码无法执行,因为当我想执行out 方法时无法解锁。 BTW,不管我在set()还是out()注释掉解锁,程序都会这样执行:
Thread[Thread-1,5,main]....生产....chicken1
Thread[Thread-2,5,main]....消费..........chicken1
Thread[Thread-0,5,main]....生产....chicken2
Thread[Thread-3,5,main]....消费..........chicken2 ......
我想了很久,还是不明白。刚学,可能理解有误,望高人指教。 请原谅我糟糕的英语。非常感谢。我的代码在这里:
package Thread;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class ThreadStudying {
public static void main(String[] args) {
Resource r = new Resource();
Thread t0 = new Thread(new Producer(r));
Thread t1 = new Thread(new Producer(r));
Thread t2 = new Thread(new Consumer(r));
Thread t3 = new Thread(new Consumer(r));
t0.start();
t1.start();
t2.start();
t3.start();
}
static class Resource {
private String name;
private int count = 1;
boolean isOut = false;
Lock lock = new ReentrantLock();
Condition pro_con = lock.newCondition();
Condition consu_con = lock.newCondition();
public void set(String name) {
lock.lock();
try {
while (isOut) {
try {
pro_con.await();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
this.name = name + count;
System.out.println(Thread.currentThread() + "....Produce...." + this.name);
count++;
isOut = true;
consu_con.signal();
}
finally {
lock.unlock();
}
}
public void out() {
lock.lock();
try {
while (!isOut) {
try {
consu_con.await();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread() + "....Consume.........." + this.name);
isOut = false;
pro_con.signal();
}
finally {
//lock.unlock();
}
}
}
static class Producer implements Runnable {
Resource r;
Producer(Resource r) {
this.r = r;
}
public void run() {
while (true) {
r.set("chicken");
try {
Thread.sleep(500);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
static class Consumer implements Runnable {
Resource r;
Consumer(Resource r) {
this.r = r;
}
@Override
public void run() {
while (true) {
r.out();
try {
Thread.sleep(500);
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
【问题讨论】:
标签: java multithreading locking java-threads