[英]java concurrency condition opportune usage
在應用程序中,當按下“創建”按鈕時,會彈出另一個子窗體。主窗體將等待直到子窗體被填充,然后單擊子窗體中的“提交”按鈕,此后,它將獲取輸入到子窗體中的數據以進行進一步處理。
我面臨的問題是程序在單擊“創建”按鈕后掛起,盡管顯示了子窗體。
waitTillFilled是應用程序中使用的條件。
動作監聽器的主要形式
if(e.getSource()==create)
{ try
{
lock.lock();
try
{
model=(DefaultTableModel)table.getModel();
Form newForm=new Form();
System.out.println("Waiting to fill the sub form");
waitTillFilled.await();
System.out.println("Waiting done....");
Vector<String> newData=newForm.returnFields();
System.out.println("added row is "+newData);
model.addRow(newData);
System.out.println("Table created"+data);
}
finally
{
lock.unlock();
}
}
catch (InterruptedException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
Thread.currentThread().interrupt();
}
}
子表單中的動作偵聽器
if(e.getSource()==submit)
{
String n,p,em;
n=name.getText();
p=phone.getText();
em=email.getText();
rowData=new Vector<String>();
rowData.add(n);
rowData.add(em);
rowData.add(p);
System.out.println("added row is "+rowData);
waitTillFilled.signal();
}
您正在嘗試在這里重新發明輪子。 您應該只使用JOptionPane
創建一個模式對話框,該對話框返回一些用戶輸入的輸入。 參見http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html
將await()從UI線程傳輸到blockingMethod(),該方法會生成一個新線程,以等待發出信號時從子表單中收集數據。
Runnable r2=new Runnable(){
@Override
public void run()
{
try
{ lock.lock();
System.out.println("Lock acquired in blockingMethod");
System.out.println("about to wait");
waitTillFilled.await();
System.out.println("Waiting done....");
Vector<String> newData=returnFields();
System.out.println("added row is "+newData);
model.addRow(newData);//add row
System.out.println("Table created"+data);
//invoke setName after reaquiring lock
lock.unlock();
System.out.println("Lock released in blockingMethod");
}
catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}};
子表單中的actionListener被編輯為
lock.lock();
System.out.println("Lock acquired in actionPerformed");
try
{
System.out.println("Waiting to fill the sub form");
model=(DefaultTableModel)table.getModel();
Form newForm=new Form();
lock.unlock();
blockingMethod();
}
finally
{
lock.unlock();
System.out.println("Lock released in actionPerformed");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.