java 线程

kouwenlong 2012-09-22 04:16:37
trButton.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent event) {
timer.schedule(new timertask(loginFrame), 0, 1000*30*loginFrame.getti());//时间间隔30秒
}
});

public class timertask extends TimerTask{

private LoginFrame loginFrame;

public timertask(LoginFrame loginFrame) {
// TODO Auto-generated constructor stub
this.loginFrame = loginFrame;
}

public void run(){

GetcThread getcthread = new GetcThread(loginFrame);
Thread t = new Thread(getcthread);
t.start();
}
}

我通过点击按钮产生一个线程,我现想下一次点击按钮的时候,结束上一个线程,如何实现?大意就是每次只希望有一个除了main之外只有一个这样的线程正在执行。
...全文
200 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
dracularking 2012-09-27
  • 打赏
  • 举报
回复
关闭旧线程后,最好判断下旧线程是否已结束工作状态来决定创建新线程的时机
Thread::isAlive() Thread::getState() ...
  • 打赏
  • 举报
回复
楼长受教了 0 0~
brightyq 2012-09-22
  • 打赏
  • 举报
回复
测试类

public class Test {

public static void main(String[] args) {
try {
ThreadTest tt = new ThreadTest();
ThreadTest.flag = true;
new Thread(tt).start();
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}

ThreadTest.flag = false;

try {
Thread.sleep(1000);
ThreadTest tt1 = new ThreadTest();
ThreadTest.flag = true;
new Thread(tt1).start();
} catch (InterruptedException e) {
e.printStackTrace();
}
}

}

class ThreadTest implements Runnable{

public static boolean flag = false;

public void run(){
while(flag){
try {
Thread.sleep(100);
System.out.println(Thread.currentThread() + "is running.");
} catch (InterruptedException e) {
e.printStackTrace();
}

}
}
}
kouwenlong 2012-09-22
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 的回复:]

新创建的一个线程时,把已创建的线程终止。

可以在线程类中设一个标志位变量,新创建线程时,将变量置0,线程终止;
然后再创建线程,将标志位置1

参考网上同学们的例子
http://blog.csdn.net/DoDChung/article/details/1832444
[/Quote]
我可能产生好多线程呢,那如何实现?最好有简单的代码啊
aikaibo 2012-09-22
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 的回复:]

新创建的一个线程时,把已创建的线程终止。

可以在线程类中设一个标志位变量,新创建线程时,将变量置0,线程终止;
然后再创建线程,将标志位置1

参考网上同学们的例子
http://blog.csdn.net/DoDChung/article/details/1832444
[/Quote]
正解..
brightyq 2012-09-22
  • 打赏
  • 举报
回复
新创建的一个线程时,把已创建的线程终止。

可以在线程类中设一个标志位变量,新创建线程时,将变量置0,线程终止;
然后再创建线程,将标志位置1

参考网上同学们的例子
http://blog.csdn.net/DoDChung/article/details/1832444
kouwenlong 2012-09-22
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 的回复:]

我的想法就是把他放到一个池子里面用队列来处理 。
[/Quote]
能具体说下吗?是不是线程进队列,然后正常结束之后,出队列?
  • 打赏
  • 举报
回复
我的想法就是把他放到一个池子里面用队列来处理 。

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧