2012-03-30 99 views
3

是否可以调用wait方法,另一个线程,而不是目前thread.what我问的是这样的:等待调用特定线程

代码:

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进入等待状态?

回答

6

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

1

我不这么认为。线程B可以检查一些变量,例如布尔值暂停;如果它是真的,它可以等待。它需要不稳定或需要同步,并且需要将其唤醒,但这取决于您希望执行的操作。

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

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++; 
     } 
    } 
} 
1

不行,你只能控制当前线程,如果你等待你实际调用wait(另一个线程(你所指的线程)作为显示器。所以你要么必须超时,要么有人在该对象上调用中断,以使当前线程再次启动。

你必须建立一个逻辑到你的程序,使其等待一个变量或消息后进行标记。另一种方法是使用锁或信号量。

你也可以拨打该线程中断,如果你想让它停下来,但逻辑也必须内置到你的程序,因为它可能只是抛出一个InterruptedException如果线程在做IO。