我在处理 java 中的线程通信时遇到问题。我正在做一个项目,将人们连接到 3 个不同的电梯(取决于他们想去的楼层),这些电梯有容量限制。问题是我有三个困难。
我的代码是基于消费者-生产者问题的,我不知道如何更改它,因此电梯不会等待它满员,而是在一段时间后自行启动。
另一个是程序在完成循环之前停止。(不知道为什么)。
如果我尝试检查是否没有选择电梯(通过获取容量)并且不显示它返回 0 楼的信息,则程序不起作用。
我的代码:(电梯 2 和 3 的类和它们的缓冲区是相同的)
public class Proba { //test class
public static void main(String[] args) {
Pojemnik c = new Pojemnik();
Pojemnik1 d = new Pojemnik1();
Pojemnik2 e = new Pojemnik2();
Winda p1 = new Winda(c, 1);
Winda1 p2 = new Winda1(d, 2);
Winda2 p3 = new Winda2(e, 3);
Osoba c1 = new Osoba(c, d, e, 1);
p1.start();
p2.start();
p3.start();
c1.start();
}
}
class Osoba extends Thread //person class
{
private Pojemnik pojemnik;
private Pojemnik1 pojemnik1;
private Pojemnik2 pojemnik2;
private int number;
public Osoba(Pojemnik c, Pojemnik1 d, Pojemnik2 e, int number) {
pojemnik = c;
pojemnik1 = d;
pojemnik2 = e;
this.number = number;
}
public void run() {
int value = 0;
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++)
{
int k=0;
while (k==0){ //i dont; want floor 0
k = -2 + (int)(Math.random()*7);} //choosing floor
int h;
if(k>-3&&k<1){ //decision which elevator
value = pojemnik.get(); // getting possible capacity
if(value>0){
pojemnik.put(value-1);} //lowering capacity
h=5-value; // how many people are already in
System.out.println("Ktos wsiadl do windy #1"
//+ this.number
+ " jest w niej " + h + " osob i wybrano pietro nr " + k);
}
if(k>-1&&k<4){
value = pojemnik1.get();
if(value>0){
pojemnik1.put(value-1);}
h=5-value;
System.out.println("Ktos wsiadl do windy #2"
//+ this.number
+ " jest w niej " + h + " osob i wybrano pietro nr " + k);
}
if(k>3&&k<8){
value = pojemnik2.get();
if(value>0){
pojemnik1.put(value-1);}
h=5-value;
System.out.println("Ktos wsiadl do windy #3"
//+ this.number
+ " jest w niej " + h + " osob i wybrano pietro nr " + k);
}
}
}
}
}
//import java.util.*;
//import java.lang.*;
class Pojemnik //buffor class
{
private int contents;
private boolean available = false;
public synchronized int get() {
while (available == false) {
try {
wait();
}
catch (InterruptedException e) {
}
}
available = false;
notifyAll();
return contents;
}
public synchronized void put(int value) {
while (available == true) {
try {
wait();
}
catch (InterruptedException e) {
}
}
contents = value;
if(value>5){ //way to never get too high capacity
contents=5;
}
available = true;
notifyAll();
}
}
// import java.lang.*; // elevator class
class Winda extends Thread {
private Pojemnik pojemnik; //bufor
private int number;
public Winda(Pojemnik c, int number) {
pojemnik = c;
this.number = number;
}
public void run() {
for (int i = 0; i < 10; i++) {
//pojemnik.get();
pojemnik.put(5); // the elevator is empty 5 people can go in
System.out.println("Winda #" + this.number
+ " jest na poziomie 0 "); //info that elevator is on floor 0
try {
sleep((int)(Math.random() * 100));
} catch (InterruptedException e) { }
}
}
}