abc*_*abc 3 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++;
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
是否有可能在点击等待按钮时bthread进入等待状态?
你想要bthread实际暂停执行,不管它在做什么?AFAIK没有办法做到这一点.但是,您可以bthread在某些共享状态同步对象(例如,CountDownLatch或Semaphore,查看java.util.concurrent包)上设置轮询,以便您更改对象的状态以设置bthread等待.
| 归档时间: |
|
| 查看次数: |
351 次 |
| 最近记录: |