0

我需要编写一个 JApplet 停止方法,该方法通过在小程序最小化时向第二个线程发送一个 suspend() 消息来挂起第二个线程。然后,当小程序未最小化时,我必须恢复线程。

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
4

1 回答 1

1

您可以使用标志和睡眠循环来实现挂起功能。

将新的布尔字段添加到您的Counter线程:

private volatile boolean isSuspended = false;

Counter给线程添加控制方法:

public suspendCounter() {
    isSuspended = true;
}

public resumeCounter() {
    isSuspended = false;
}

将额外的睡眠循环添加到您的运行方法中,该方法在 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) {
        }
    }
}
于 2013-05-09T15:07:35.443 回答