java – 等待特定线程的调用

是否可以为另一个线程而不是当前线程调用wait方法.我要问的是这样的:

码:

public class a extends JApplet{
 JButton start= new JButton("Start");
 JButton wait= new JButton("Wait");
 JButton notify = new JButton("Notify");
 final Thread bthread = new Thread(new B(), "BThread");

 @Override
 public void init(){
    //start
   this.getContentPane().setLayout(new FlowLayout()); 
   start.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Started");
        }
    });
   this.getContentPane().add(start);
   //wait
   wait.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Waited");
            synchronized(bthread)       //something like this
            {
                try {
                    bthread.wait();     //is it possible instead of the current thread the bthread get invoke
                 } catch (Exception ex) {
                    Logger.getLogger(a.class.getName()).log(Level.SEVERE, null, ex);
                }}
        }
    });
   this.getContentPane().add(wait);

   //notify
   notify.addActionListener(new ActionListener() {
         @Override
        public void actionPerformed(ActionEvent e) {
            System.out.println("Notified");
            synchronized(a.this){
             a.this.notify();
            }}
    });
   this.getContentPane().add(notify);
 }
class B implements Runnable
{
    int i=0;
   @Override
    public void run() {
        while(i<10){
            System.out.println(" i = "+i);
           // i++;
        }
    }
}
}

是否有可能在单击等待按钮时bthread进入等待状态?

最佳答案
你想让bthread真正暂停执行,无论它在做什么? AFAIK没有办法做到这一点.但是,您可以在某些共享状态同步对象(例如,CountDownLatchSemaphore,查看java.util.concurrent程序包)上设置bthread轮询,以便您更改对象的状态以设置bthread等待.

转载注明原文:java – 等待特定线程的调用 - 代码日志