Java 挂起applet中的线程
我需要编写一个JApplet stop方法,当applet最小化时,通过向第二个线程发送suspend()消息来挂起第二个线程。然后,当小程序未动画化时,我必须恢复线程Java 挂起applet中的线程,java,multithreading,swing,japplet,suspend,Java,Multithreading,Swing,Japplet,Suspend,我需要编写一个JApplet stop方法,当applet最小化时,通过向第二个线程发送suspend()消息来挂起第二个线程。然后,当小程序未动画化时,我必须恢复线程 import javax.swing.*; import java.awt.*; public class StopResume extends JApplet { private final static int THREADS = 3; private Counter[] t = new Counter[T
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
import javax.swing.*;
导入java.awt.*;
公共类StopResume扩展了JApplet
{
私有最终静态int线程=3;
私有计数器[]t=新计数器[线程];
私有JTextField[]tf=新的JTextField[THREADS];
公共void init()
{
最终整数文本字段大小=5;
JLabel title=新的JLabel(“JTextFields由不同的线程更改”),
subtitle=新的JLabel(“最小化小程序结果为-”);
JLabel[]标签={
新的JLabel(“线程#1被停止,计数被重置:”),
新JLabel(“线程2被挂起,计数恢复:”),
新的JLabel(“线程3不受影响,计数继续:”)
};
容器c=getContentPane();
c、 setLayout(新的FlowLayout());
c、 增加(标题);
c、 增加(副标题);
对于(int i=0;i
您可以使用标志和休眠循环实现挂起功能
将新的布尔字段添加到计数器线程:
private volatile boolean isSuspended = false;
public suspendCounter() {
isSuspended = true;
}
public resumeCounter() {
isSuspended = false;
}
将控制方法添加到计数器
线程:
private volatile boolean isSuspended = false;
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) {
}
}
}
for(int i=0;i
您已经描述了一个问题,但到目前为止还没有提出任何问题(更不用说具体的、可回答的问题了)。你的问题是什么?suspend()是一个不推荐使用的方法。