我不理解我的错误,我会描述它然后我会发布我的代码。 从main()我想运行3个线程(每个线程包含3个女性的循环)。 我有一个方法打印每个进入浴室的女人和每个女人。我想使用锁定,所以每个线程中的每3个女人都会在下一个帖子发生之前写出。输出应该是这样的: 女人0进入浴室 女人0退出浴室 女人1进入浴室 女人1离开浴室 女人2进入浴室 女人2离开浴室 然后每个线程2次。 我的问题是,只有一个线程正在写入,2个没有到达锁定仍在等待我释放锁定后。 这是我的代码:( BathRoom类)
private Lock lockW=new ReentrantLock();
public int women_present;
public BathRoom(){
women_present=0;//empty at start
}
public void woman_wants_to_enter (int i) {
lockW.lock();
women_present++;
System.out.println ("Woman " + i + " enters bathroom "); }
public void woman_leaves (int i) {
try {
Thread.sleep (1000);
}catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println ("Woman " + i + " exits bathroom ");
if((women_present%3)==0){
women_present=0;
lockW.unlock();
} }
这是女性班:
private int i; /* This identifies the woman. */
private BathRoom bathroom;
public Woman (BathRoom bathroom,int i) {
this.i = i;
this.bathroom = bathroom;
}
public void run () {
for (int i = 0; i < 3; i++) {
try {
Thread.sleep ((long) (500 * Math.random()));
}catch (InterruptedException e) {
e.printStackTrace();
}
bathroom.woman_wants_to_enter (i);
bathroom.woman_leaves (i);
}
}}
答案 0 :(得分:1)
我冒昧地修改你的代码:
package stackoverflow;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
class BathRoom {
private Lock lockW=new ReentrantLock();
private Condition c1=lockW.newCondition();
public int women_present;
public BathRoom(){
women_present=0;//empty at start
}
public void woman_wants_to_enter (int i) {
lockW.lock();
while(women_present!=i)
try {
c1.await();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println ("Woman " + i + " enters bathroom "); }
public void woman_leaves (int i) {
try {
Thread.sleep (1000);
}catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println ("Woman " + i + " exits bathroom ");
women_present++;
if(women_present==3){
women_present=0;
}
c1.signal();
lockW.unlock();
}
}
class Woman implements Runnable{
private int i; /* This identifies the woman. */
private BathRoom bathroom;
public Woman (BathRoom bathroom,int i) {
this.i = i;
this.bathroom = bathroom;
}
public void run () {
for (int i = 0; i < 3; i++) {
try {
Thread.sleep ((long) (500 * Math.random()));
}catch (InterruptedException e) {
e.printStackTrace();
}
bathroom.woman_wants_to_enter (i);
bathroom.woman_leaves (i);
}
}
}
public class testdummy {
public static void main(String[] args) {
BathRoom b=new BathRoom();
Woman w0=new Woman(b, 0);
Woman w1=new Woman(b, 1);
Woman w2=new Woman(b, 2);
Thread A=new Thread(w0);
Thread B=new Thread(w1);
Thread C=new Thread(w2);
A.start();
B.start();
C.start();
}
}
我已经使用 Condition对象来同步线程访问方法 ,它不完美但它有效,希望它会给你一个更好的方法的想法
答案 1 :(得分:0)
第一个帖子 在woman_wants_to_enter()中, 线程获取lock()继续。 woman_present设置为1。
在woman_leaves()中,woman_present仍为1 if(1 mod 3为1)因此不会调用解锁
第二个线程进入woman_wants_to_enter(),但正在等待锁定