###前提・実現したいこと
課題で簡単なStopwatchを作っています。
JButtonで作ったスタートボタンを押すと、waitになっていたオブジェクトをnotifyするように作りたいです。
デッドロックが原因だと予測しているのですが、その回避の方法がわかりません。
また、今回質問している箇所の他にもおかしな箇所があれば教えてほしいです。
###発生している問題・エラーメッセージ
ボタン自体は動作しているのですが、notifyが動作しません。
おそらく、waitとnotifyどちらもsynchronizedにしているので、デッドロックになってしまっていると予測しています。
###該当のソースコード
java
1public class stopwatch2 extends JPanel{ 2 static JLabel label; 3 JButton b1,b2,b3; 4 public static final int FPS = 0; 5 private static long startTime; 6 private static boolean isRunning = false; 7 private static long time; 8 public stopwatch2(){ 9 10 label =new JLabel(String.valueOf(time)); 11 b1 = new JButton("Start"); 12 b1.addActionListener( 13 new ActionListener(){ 14 public synchronized void actionPerformed(ActionEvent event){ 15 isRunning = true; 16 notify(); 17 } 18 }); 19 b2 = new JButton("Stop"); 20 b2.addActionListener( 21 new ActionListener(){ 22 public void actionPerformed(ActionEvent event){ 23 isRunning = false; 24 } 25 }); 26 b3 = new JButton("Reset"); 27 setLayout(new BorderLayout()); 28 add(label,BorderLayout.NORTH); 29 add(b1,BorderLayout.CENTER); 30 add(b2,BorderLayout.EAST); 31 add(b3,BorderLayout.SOUTH); 32 } 33 34 public static void main(String[] args) throws InterruptedException { 35 // TODO Auto-generated method stub 36 JFrame frame = new JFrame("Stopwatch"); 37 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); 38 stopwatch2 sw = new stopwatch2(); 39 frame.add(sw); 40 frame.pack(); 41 frame.setVisible(true); 42 System.out.print(isRunning); 43 while(true){ 44 System.out.print(Thread.currentThread()); 45 synchronized(sw){ 46 sw.wait(); //swがついてるメソッドの間はsynchronizedされる 47 } 48 sw.startTime = System.currentTimeMillis();//ミリ単位の現在の時間をstartTimeに代入 49 while(sw.isRunning){ //isRunningがtrueの間ループ 50 //ラベルにtimeに入っているものを入れて更新し続ける 51 //stopを押すと、isRunningにfalseを代入してループを止める。 52 sw.label.setText(String.valueOf(System.currentTimeMillis()-startTime)); 53 sw.repaint(); 54 Thread.sleep(1000 / stopwatch2.FPS); 55 } 56 } 57 58 } 59 60} 61
###ツール
eclipseを使っています。
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/07/03 14:53
2017/07/03 14:56
2017/07/03 23:51