我现在写了个子线程,里面有个死循环,不停地从数据库读出需要的数据进行处理,界面上有个关闭按钮,请问该怎么编写,使这个按钮点击之后可以关闭这个子线程。主要就是怎么关闭子线程。
解决方案 »
- 求解hibernate一个问题,比较头痛
- bao110908(长牙了,好痛) 还在吗 ?
- =====有奖竟猜=====火箭Vs太阳===== 截止时间:4月10日-10点30分
- 谢谢~关于Thread.currentThread.destory()的问题
- 为什么我drawString的时候,总是在原来的地方继续draw,而没有擦去原来的string?
- ActionListener的用法?
- Java程序可不可以嵌入flash
- 写文件时如何不覆盖以前的内容???如何实现在文件首部追加呢?
- 请教一个JDBC调用SQL Server 存储过程的问题
- 在JAVA的APPLET中如何访问SYBASE数据库,并从数据库取出数据,请写详细代码,给分30
- 请教怎样实现一个类数据库的程序``
- 初学,碰到一道编不出来的问题,请高手指正,
。while(!stop){
// 你的一直处理的代码。
}你要做的就是在其它地方将这个 stop 设置为true 就可以了。
如果这个线程只有一个,你可以用
static boolean stop = false;这样访问起来就更简单了!
class Mythread extends Thread{
private volatile boolean stop=false; public void threadStop(){
stop=true;
}
public void run(){
try{
//init();
synchronized(this){
while(stop){
getdate();
}
}
}catch(Exception e){}
}我在主线程中调用Mythread.threadStop()中止不了
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;public class TestNewThread {
public static void main(String[] args)
throws Exception{
ExecutorService es = Executors.newCachedThreadPool(); //获得一个线程池。
Future f = es.submit( new Callable(){ //这是一个接口call就是线程执行时调用的方法(相当于runnable).
@Override
public Object call() throws Exception {
for(int i=0;i<10;i++){
System.out.println( Thread.currentThread().getId() );
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return "5.0新线程";
}
}
);
// f.cancel( true ); //停止
String str = (String)f.get();//获得线程返回值
System.out.println(str);
}
}es.submit( callable ) 就是启动一个线程。可以启动多个线程(调多次submit)
把这个指示变量设置成volatile类型,这样使线程每次访问该变量时强近它从共享内存中重读变量的值,而不是读它的副本
class Mythread extends Thread{
private volatile boolean stop=true;public void threadStop(){
stop=false;
}
public void run(){
try{
//init();
synchronized(this){
while(stop){
getdate();
}
}
}catch(Exception e){}
}
如果这样都还不行,还有一个比较贱的办法,但是会影响你的程序效率,代码如下:
class Mythread extends Thread{
private volatile boolean stop=true;public void threadStop(){
stop=false;
}
public void run(){
try{
//init();
synchronized(this){
while(stop){
if(stop==false){
break;
}else{
getdate();
}
}
}
}catch(Exception e){}
}