我已經在這裏討論了關於java多線程的幾乎所有問題,但是我不太明白我的理解是否正確。在這裏調用'wait'和'notify'
我希望瞭解操作順序是否按照下面的描述進行操作。
import javax.swing.*;
import java.awt.FlowLayout;
import java.awt.event.*;
class Runner implements Runnable{
long count = 0;
JLabel label;
boolean paused = false;
public Runner(JLabel label){
this.label = label;
}
public void run(){
while(true){
try {
if(paused){
synchronized(this){
wait();
}
}
} catch(InterruptedException e) {}
count++;
label.setText(Long.toString(count));
if(Thread.interrupted())
return;
}
}
synchronized void pause_counting(){
paused = true;
}
synchronized void start_counting(){
paused = false;
notifyAll();
}
}
public class ThreadRace extends JApplet{
boolean running = true;
Thread thread;
@Override
public void init(){
final JPanel panel = new JPanel();
panel.setLayout(new FlowLayout());
JLabel threadProgress = new JLabel("0");
final Runner runner = new Runner(threadProgress);
thread = new Thread(runner);
thread.start();
panel.add(threadProgress);
JButton toggle = new JButton("Stop");
toggle.addActionListener(new ActionListener() {
@Override
synchronized public void actionPerformed(ActionEvent e) {
System.out.println("Running: " + running);
if(running){
runner.pause_counting();
} else {
runner.start_counting();
}
running = !running;
}
});
panel.add(toggle);
add(panel);
}
public void stop(){
thread.interrupt();
}
}
這是如何工作的?
- 當我調用方法
pause_counting()
時,我將暫停設置爲false。 - 在run()的內部,我抓住了
synchronized(this) { ... }
塊內的對象runner
的鎖。 - 當我打電話給
this.wait()
時,我釋放了我剛纔擁有的同一把鎖,並進入WAITING
狀態。 - 在這一點上,任何其他方法可以自由地做任何事情
runner
(!) - 我最終打電話給
start_counting()
。 - 這使線程回到
RUNNING
狀態,並從wait()語句之後繼續。雖然它仍是synchronized(this)
塊內,它就會被持有鎖的 - 然而,一旦離開塊,它釋放鎖,並繼續執行
我敢肯定有一些缺陷在我理解。
幫助? :(
不是一個答案,但相關(和**強烈推薦**):http://blog.smartbear.com/programming/why-johnny-cant-write-multithreaded-programs/ –
你的第一個錯誤是在不同的同步「Runner」的實例。 –
我理解,理想情況下,所有三個應該在同一個顯示器上同步。但是,我明確希望瞭解使用'this'的效果。也許這不完全是最好的例子...... – peteykun