注意这个新的线程一定要在开始事件中创建,例如:
Thread thread1=new Thread();
这句一定放在开始事件中
Thread thread1=new Thread();
这句一定放在开始事件中
解决方案 »
- java 日期格式
- 如何把jar及其Lib做成一个完全可以执行的exe。(不包括虚拟机)
- 我的WEB服务(JAVA写的)返回的的是一个String ,用C++去调用这个服务时遇到一个问题请教。谢谢!
- 自己编的Cerver.java和Client.java不能互相通信,麻烦好心人看看,谢谢!急!
- 关于snmp: westhawk.co.uk公司的java snmp开发包,接受Trap初始化异常:Socket
- 这个问题真的很奇怪~~~~~~`天才们都进来看看啊
- 想做一個WEB方式的OUTLOOK,請問JAVAMAIL怎樣創建和操作本地文件夾呢?
- 请问哪有IAS4.5或BAS4.5下载.
- 侃侃、谈谈。
- 正则表达式问题(JAVASE)
- bin和src文件是干什么用的
- 数据库更新问题(st.executeUpdate(sql))请高手指点
把线程的声明与定义放到“开始”按钮的事件处理程序内。2.线程的停止通过判断某个标记来做结束。
如果Thread thread1 = new Thread()放在“开始”按钮的事件中的话,
那么每次点击“开始”按钮,将会生成一个新的线程
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;public class TestMuchRun
extends javax.swing.JFrame
{
private boolean isRun;
FlowLayout flowLayout1 = new FlowLayout();
JButton ButtonStart = new JButton();
JButton ButtonEnd = new JButton();
class Test
implements Runnable
{
public void run()
{
while (isRun)
{
System.out.println("I am running!!!!");
Thread.currentThread().yield();
}
System.out.println("I am going!!!bye bye!!!!!!!");
}
} public TestMuchRun()
{
try
{
jbInit();
}
catch (Exception e)
{
e.printStackTrace();
}
} private void jbInit() throws Exception
{
this.setBounds(0,0,500,500);
ButtonStart.setText("Start");
ButtonStart.addMouseListener(new TestMuchRun_ButtonStart_mouseAdapter(this));
this.getContentPane().setLayout(flowLayout1);
ButtonEnd.setVerifyInputWhenFocusTarget(true);
ButtonEnd.setText("End");
ButtonEnd.addMouseListener(new TestMuchRun_ButtonEnd_mouseAdapter(this));
this.getContentPane().add(ButtonStart, null);
this.getContentPane().add(ButtonEnd, null);
} void ButtonStart_mouseClicked(MouseEvent e)
{
isRun = true;
new Thread(new Test()).start();
} void ButtonEnd_mouseClicked(MouseEvent e)
{
isRun = false;
} public static void main(String[] args)
{
TestMuchRun t = new TestMuchRun();
t.setVisible(true);
}
}
class TestMuchRun_ButtonStart_mouseAdapter
extends java.awt.event.MouseAdapter
{
TestMuchRun adaptee; TestMuchRun_ButtonStart_mouseAdapter(TestMuchRun adaptee)
{
this.adaptee = adaptee;
} public void mouseClicked(MouseEvent e)
{
adaptee.ButtonStart_mouseClicked(e);
}
}class TestMuchRun_ButtonEnd_mouseAdapter
extends java.awt.event.MouseAdapter
{
TestMuchRun adaptee; TestMuchRun_ButtonEnd_mouseAdapter(TestMuchRun adaptee)
{
this.adaptee = adaptee;
} public void mouseClicked(MouseEvent e)
{
adaptee.ButtonEnd_mouseClicked(e);
}
}
Thread thread1 = new Thread()
thread1.start();
如你所說﹐用stop方法不安全﹐可用如下方法代替
class YourThread extends Thread{
private boolean stopThread;
public void requestStop(){
stopThread = true;
}
public void run(){
while(!stopThread){
...
}
}
}要停止時調用線程的requestStop方法如果你不是要中止線程﹐而是要使其暫停的話﹐可以調用線程的wait()方法﹐喚醒線程用notifyAll()方法
你可以注意对线程状态的描述,线程终止后其状态叫做dead死人又怎么能复活呢?:)
谢谢大家,特别感谢feiyuegaoshan(飞跃) !