Блокировка не снимается потоком в конце метода выполненияJAVA

Программисты JAVA общаются здесь
Ответить Пред. темаСлед. тема
Anonymous
 Блокировка не снимается потоком в конце метода выполнения

Сообщение Anonymous »

Итак, я пытаюсь запустить симуляцию кафе, используя Java ReentrantLock и Летучий. По сути, у меня есть временной поток, который должен изменить изменчивую переменную на false, чтобы остановить работу всех остальных потоков. Но по какой-то причине поток Time не снимает блокировку, и другие потоки продолжают работать бесконечно.
Вот код основного класса:

Код: Выделить всё

package cafesim;

import java.time.Instant;
import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

public class CafeSim {

public static volatile boolean continuetoRun = true;

static Queue OutsideQueue = new LinkedList();
static Queue InsideQueue = new LinkedList();

static ReentrantLock QueueLock = new ReentrantLock();
static Condition QueueCon = QueueLock.newCondition();

public static void main(String[] args) {

new Time(Instant.now().getEpochSecond()).start();
new Table().start();

}

}

}
Вот код класса Table:

Код: Выделить всё

public class Table extends Thread{

String choice;

public void run(){

while(CafeSim.continuetoRun == true){
CafeSim.QueueLock.lock();

if(CafeSim.OutsideQueue.isEmpty() && CafeSim.continuetoRun == true)
try {
CafeSim.QueueCon.signal();
CafeSim.QueueCon.await();

} catch (InterruptedException ex) {
Logger.getLogger(Table.class.getName()).log(Level.SEVERE, null, ex);
}

else if(CafeSim.InsideQueue.size() == 10 && CafeSim.continuetoRun == true){
System.out.println("Seats inside filled, please wait!");

try {
CafeSim.QueueCon.await();
} catch (InterruptedException ex) {
Logger.getLogger(Table.class.getName()).log(Level.SEVERE, null, ex);
}
}

else if (CafeSim.OutsideQueue.size() != 0 && CafeSim.continuetoRun == true){
if(CafeSim.OutsideQueue.peek().choice == 1){
choice = "juice";
}
else {
choice = "coffee";
}

System.out.println(CafeSim.OutsideQueue.peek() + " is at the table and has ordered " + choice + "!");
CafeSim.InsideQueue.add(CafeSim.OutsideQueue.poll());
CafeSim.QueueCon.signal();
CafeSim.QueueLock.unlock();
}
else {
break;
}
}

System.out.println("This should end[Table].");
CafeSim.QueueCon.signal();
CafeSim.QueueLock.unlock();

}
}
А вот класс времени:

Код: Выделить всё

public class Time extends Thread{

private long startTime;
private long currentTime;
boolean lastordersinformed = false;

public Time(long timeatStart){
this.startTime = timeatStart;
}

public void run(){

while(CafeSim.continuetoRun == true){
CafeSim.QueueLock.lock();
currentTime = Instant.now().getEpochSecond();

if(currentTime - startTime < 20){
try {
CafeSim.QueueCon.signal();
CafeSim.QueueCon.await();
} catch (InterruptedException ex) {
Logger.getLogger(Time.class.getName()).log(Level.SEVERE, null, ex);
}
}

else if (currentTime - startTime > 20 && lastordersinformed == false){

System.out.println("LAST ORDERS RESTAURANT WILL CLOSE VERY SOON!");
CafeSim.OutsideQueue.clear();
//Waiter.timeToLeave = true;
lastordersinformed = true;

try {
CafeSim.QueueCon.signal();
CafeSim.QueueCon.await();
} catch (InterruptedException ex) {
Logger.getLogger(Time.class.getName()).log(Level.SEVERE, null, ex);
}
}

else if(currentTime - startTime > 30 &&  lastordersinformed == true){

CafeSim.continuetoRun = false;
System.out.println("Cafe is closed.");

}

else{
try {
CafeSim.QueueCon.signal();
CafeSim.QueueCon.await();
} catch (InterruptedException ex) {
Logger.getLogger(Time.class.getName()).log(Level.SEVERE, null, ex);
}
}

}

System.out.println("Thread has ended.[Time]");
CafeSim.QueueCon.signal();
CafeSim.QueueLock.unlock();

}

}
Оба потока должны завершиться через 30 секунд, но по какой-то причине этого не происходит. Только нить времени подходит к концу.

Подробнее здесь: https://stackoverflow.com/questions/618 ... run-method
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «JAVA»