时间:2022-12-01 10:56:16 | 栏目:JAVA代码 | 点击:次
Java线程关闭,总的来说有3种:
1.使用状态位,这个简单,就不多说了:
private volatile boolean flag= true;
public void stopTask() {
flag = false;
}
@Override
public void run() {
while(flag){
/* do your no-block task */
}
}
}
public class BlockTask extends Thread {
@Override
public void run() {
try {
while (!Thread.interrupted()) {
/* do your block task*/
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
@Override
public void run() {
try {
sleep(10000);
} catch (InterruptedException e) {
System.out.println("if yout use interrupt you will see me");
}
}
public static void main(String[] args)throws Exception {
// TODO Auto-generated method stub
BlockTask task = new BlockTask();
task.start();
Thread.sleep(1000);
task.interrupt();
}
}
private volatile ServerSocket server;
public void stopTask(){
try {
if(server!=null){
server.close();
System.out.println("close task successed");
}
} catch (IOException e) {
System.out.println("close task failded");
}
}
@Override
public void run() {
try {
server = new ServerSocket(3333);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws InterruptedException {
SocketTask task = new SocketTask();
task.start();
Thread.sleep(1000);
task.stopTask();
}
}