java并发条件适宜用法

时间:2014-02-01 20:25:06

标签: java concurrency

在按下“创建”按钮的应用程序中,弹出另一个子窗体。主窗体等待,直到填充子窗体并单击子窗体中的提交按钮,之后它将获取在子窗体中输入的数据进一步处理。

我遇到的问题是程序在单击“创建”按钮后挂起,但显示子窗体。

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();

    }

2 个答案:

答案 0 :(得分:1)

你正试图在这里重新发明轮子。您应该使用JOptionPane创建一个模式对话框,返回一些用户输入的输入。见http://docs.oracle.com/javase/tutorial/uiswing/components/dialog.html

答案 1 :(得分:0)

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");
            }