Я в основном пытаюсь реализовать пример реальной жизни нескольких людей, бронирующих одно онлайн-такси. Здесь, в моем коде, у меня есть 3 класса - такси, клиент и сервер.
Должно быть несколько клиентов (нитей) и одно такси. Но я не могу этого сделать. Каждый раз, когда я создаю нового клиента, создается новый экземпляр такси.
Это класс такси код-
Не удалось добиться синхронизации в многопоточности
public class taxi {
boolean BOOKED=false;
String id;
void book(){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
BOOKED=true;
System.out.println("Customer "+Thread.currentThread().getName()+" BOOKED taxi");
}
void release(){
BOOKED=false;
System.out.println("Customer "+Thread.currentThread().getName()+" RELEASED taxi");
}
void setId(String id){
this.id=id;
}
String getId(){
return id;
}
}
класс клиента код-
public class customer extends Thread {
taxi t=new taxi();
public void run(){
//System.out.println(t.hashCode());
t.setId(Thread.currentThread().getName());
System.out.println("Customer "+Thread.currentThread().getName()+" trying to BOOK taxi");
t.book();
System.out.println("Customer "+Thread.currentThread().getName()+" is currently USING taxi");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Customer "+Thread.currentThread().getName()+" RELEASING taxi");
t.release();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("taxi used by customer "+Thread.currentThread().getName()+" set id to "+t.getId());
}
}
серверный класс код-
public class server {
public static void main(String args[]){
customer A=new customer();
customer B=new customer();
customer C=new customer();
customer D=new customer();
Thread t=new Thread();
A.setName("A");
B.setName("B");
C.setName("C");
D.setName("D");
A.start();
B.start();
C.start();
D.start();
}
}
Это мой output-
Customer B trying to BOOK taxi
Customer D trying to BOOK taxi
Customer A trying to BOOK taxi
Customer C trying to BOOK taxi
Customer B BOOKED taxi
Customer A BOOKED taxi
Customer A is currently USING taxi
Customer D BOOKED taxi
Customer D is currently USING taxi
Customer B is currently USING taxi
Customer C BOOKED taxi
Customer C is currently USING taxi
Customer C RELEASING taxi
Customer C RELEASED taxi
Customer D RELEASING taxi
Customer D RELEASED taxi
Customer A RELEASING taxi
Customer A RELEASED taxi
Customer B RELEASING taxi
Customer B RELEASED taxi
taxi used by customer D set id to D
taxi used by customer C set id to C
taxi used by customer A set id to A
taxi used by customer B set id to B
Как вы можете видеть, идентификатор каждого такси отличается от другого.
Просьба помочь.
Как вы думаете, 'такси t = новое такси();' как поле внутри 'customer'? –
он создает экземпляр такси в клиенте. Я знаю, что это основная причина моей проблемы, но я не могу понять, как это сделать. –
Создайте один экземпляр «taxi» и поделитесь им с вашими «клиентскими» экземплярами.Вы узнали о аргументах конструктора раньше? –