有兩種方法將消息推送到arraylist,其他方法從arraylist中檢索消息。兩種方法都是同步的。 我創建了兩個線程,一個將消息推送到arraylist和其他檢索。兩個線程都處於僵局situation.How來解決它兩個線程正在等待對方,無法解析
下面是推動代碼和顯示信息
public class FetchCurrentTime {
static final int MAXMESSAGE = 5;
private List<String> messages = new ArrayList<String>();
public synchronized void putTime(){
while(messages.size() != MAXMESSAGE){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
messages.add(dateFormat.format(cal.getTime()).toString());
}
notify();
}
public synchronized String getTime(){
String message= "Unable to fetch time";
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
if(!message.isEmpty()){
message = messages.remove(messages.size()-1);
}
notify();
return message;
}
}
下面是生產者和消費者代碼
public class ProduceTime extends Thread {
FetchCurrentTime fc ;
public ProduceTime(FetchCurrentTime fc) {
this.fc = fc;
}
@Override
public void run() {
fc.putTime();
}
}
public class ConsumeTime extends Thread {
FetchCurrentTime fc ;
public ConsumeTime(FetchCurrentTime fc) {
this.fc = fc;
}
@Override
public void run() {
while (true) {
String time = fc.getTime();
System.out.println(time);
}
}
}
這裏是代碼去測試。
public class GetDate {
public static void main(String[] args) throws InterruptedException {
FetchCurrentTime fc = new FetchCurrentTime();
ProduceTime p = new ProduceTime(fc);
ConsumeTime c = new ConsumeTime(fc);
Thread t1 = new Thread(p);
Thread t2 = new Thread(c);
t1.start();
t2.start();
}
}
用文字描述你的'putTime'在做什麼。 –
你在測試等待和通知方法嗎?現代Java代碼不使用通知和等待。在多線程應用程序中存在更高階的類和方法。 –
@SotiriosDelimanolis putTime獲取當前時間並將時間添加到字符串的數組列表中。我使putTime和getTime方法同步,以便putTime將消息插入到arraylist中,getTime不應該從arraylist中檢索消息並顯示它 – Raghu