2013-05-08 197 views
1

我需要編寫一個JApplet停止方法,該方法通過在applet最小化時向第二個線程發送suspend()消息來掛起第二個線程。然後,當小程序未被最小化時,我必須恢復線程。在applet中掛起線程

import javax.swing.*; 
import java.awt.*; 

public class StopResume extends JApplet 
{ 
    private final static int THREADS = 3; 
    private Counter[] t = new Counter[THREADS]; 
    private JTextField[] tf = new JTextField[THREADS]; 

    public void init() 
    { 
    final int TEXTFIELD_SIZE = 5; 
    JLabel title = new JLabel("JTextFields are changed by different threads."), 
      subtitle = new JLabel("Minimizing applet results in -"); 
    JLabel[] labels = { 
         new JLabel("Thread#1 being stopped, count gets reset: "), 
         new JLabel("Thread#2 being suspended, count resumed:"), 
         new JLabel("Thread#3 not affected, count continues:  ") 
         }; 
    Container c = getContentPane(); 

    c.setLayout(new FlowLayout()); 
    c.add(title); 
    c.add(subtitle); 
    for (int i = 0; i < THREADS; i++) 
    { 
     tf[i] = new JTextField(TEXTFIELD_SIZE); 
     c.add(labels[i]); 
     c.add(tf[i]); 
     t[i] = new Counter(tf[i]); 
     t[i].start(); 
    } 
    } // End of init method definition 
    public void stop() 
    { 

    } 

    public void start() 
    { 

    } 
} // End of StopResume class definition 

class Counter extends Thread 
{ 
    private JTextField tf; // the JTextField where the thread will write 

    public Counter(JTextField tf) 
    { 
    this.tf = tf; 
    } 

    public void run() 
    { 
    final int ONE_SECOND = 1000; // in milliseconds 

    for (int i = 0; i < Integer.MAX_VALUE; i++) 
    { 
     tf.setText(Integer.toString(i)); 
     try 
     { 
     sleep(ONE_SECOND); 
     } 
     catch(InterruptedException ie) 
     { 
     } 
    } 
    } // End of run method definition 
} // End of Counter class definition 
+1

你已經描述了一個問題,但至今沒有問過問題(更不用說具體的可回答的問題)。你的問題是什麼? – 2013-05-09 02:50:33

+0

suspend()是一個不推薦的方法。 http://docs.oracle.com/javase/7/docs/technotes/guides/concurrency/threadPrimitiveDeprecation.html – vptheron 2013-05-09 13:57:12

回答

1

您可以使用標誌和休眠循環來實現掛起功能。

新的布爾字段添加到您的Counter螺紋:

private volatile boolean isSuspended = false; 

添加控制方法Counter螺紋:

public suspendCounter() { 
    isSuspended = true; 
} 

public resumeCounter() { 
    isSuspended = false; 
} 

把額外的睡眠循環到你的run方法,迭代而isSuspended是:

for (int i = 0; i < Integer.MAX_VALUE; i++) { 
    tf.setText(Integer.toString(i)); 
    try { 
     sleep(ONE_SECOND); 
    } catch(InterruptedException ie) { 
    } 
    while (isSuspended) { 
     try { 
      sleep(100); 
     } catch(InterruptedException ie) { 
     } 
    } 
}