等待特定线程的调用

时间:2012-03-30 12:31:16

标签: java multithreading wait

是否可以为另一个线程而不是当前线程调用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是否可能进入等待状态?

4 个答案:

答案 0 :(得分:6)

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

答案 1 :(得分:3)

没有。你不能暂停这样的线程。

但是你可以在B类中实现一个wait方法:

class B implements Runnable
{
  private boolean wait = false;

  public void pause() {
    wait = true;
  }

    int i=0;
   @Override
    public void run() {
        while(i<10){
            if (wait) {
               wait();
            }
            System.out.println(" i = "+i);
           // i++;
        }
    }
}

答案 2 :(得分:1)

我不这么认为。 线程B可以检查一些变量,例如布尔暂停;如果它是真的它可以等待。它需要是易变的或需要同步,需要唤醒它,但这取决于你想要它做什么。

但是如果线程B正在进行一些长时间的操作,它可能会在检查是否应该等待之前运行很长时间。

答案 3 :(得分:1)

不,你只能控制当前线程,如果你在另一个线程上等待,你实际上使用该对象(你所指的线程)调用wait()作为监视器。所以你要么超时,要么有人在该对象上调用中断来使你的当前线程重新开始。

您必须在程序中构建该逻辑,使其在标记变量或消息后等待。另一种方法是使用锁或信号量。

如果你希望它停止,你也可以在该线程上调用中断,但是该逻辑也必须内置到你的程序中,因为如果线程正在执行IO,它可能会抛出InterruptedException。