java - 在小程序中挂起线程

标签 java multithreading swing japplet suspend

我需要编写一个 JApplet stop 方法,当小程序最小化时,通过向第二个线程发送 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

最佳答案

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

向您的 Counter 线程添加新的 boolean 字段:

private volatile boolean isSuspended = false;

Counter线程添加控制方法:

public suspendCounter() {
    isSuspended = true;
}

public resumeCounter() {
    isSuspended = false;
}

将额外的 sleep 循环添加到您的 run 方法中,该方法在 isSuspished 开启时进行迭代:

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) {
        }
    }
}

关于java - 在小程序中挂起线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16451540/

相关文章:

java - 需要帮助制作按钮继电器信息

java - 具有系统外观的 Linux 上的 JTree 背景颜色

java - 在JFrame中使用paint()时出现问题

java - Java 中的 Couchbase 连接池

ios - 多线程 : executing method calls only after finished executing other method

java - 如何使用Java找到最大的图像?

Java Swing 使线程等待一次

java - AtomicInteger 条件检查线程安全

java - Spring REST API 中的 Json 模式验证

java - 预验证类中的 Android 错误类引用解析为意外实现