java 启动新线程有三种方法:
类 Thread 直接new
接口 Runnable
接口 callable
Runnable 和Callable的区别:
Callable 可以返回值 即可return
ackage com.jwz.test;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class testThread {
private static class UserRun implements Runnable {
@Override
public void run(){
System.out.println("I am runable ");
}
}
private static class UserCall implements Callable{
@Override
public String call(){
System.out.println("I am callable");
return "CallResult";
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
UserRun run = new UserRun();
new Thread(run).start();
UserCall call=new UserCall();
//用futureTask 构造Callable对象
FutureTask<String> future=new FutureTask<String>(call);
new Thread(future).start();
System.out.println(future.get());
}
}
知识兔
线程的结束:
早期版本 用 stop(),resume(),suspend() 其中 stop() 不能释放资源 ,suspend()容易死锁。所以都不建议使用了
现在使用 interrput() 、 isInterrupted()、static 方法 interrputed()
interrput 方法用于中断一个线程(java 线程是协作式的),并不是强行关闭一个线程,只是跟这个线程打个招呼把中断线程的标志位设置为true ,是否重点又线程自己决定
isInterrupted 判断当前线程是否处于中断状态
static 方法 interrupted 判断当前线程是否处于中断状态,并把线程中断标志位设置为false
ackage com.jwz.thread;
public class EndThread {
private static class UseThread extends Thread{
public UseThread(String name){
super(name);
}
@Override
public void run(){
String threadName=Thread.currentThread().getName();
while (!isInterrupted()){
System.out.println(threadName+" is run");
}
System.out.println(threadName+" is finished and isInterrupt flag is "+isInterrupted());
}
public static void main(String[] args) throws InterruptedException {
Thread useThread=new UseThread("EndThread");
useThread.start();
sleep(20);
useThread.interrupt();
}
}
}
知识兔
线程里没有判断isInterrupted()的判断线程就不会中断
如果run() 方法 里有Thread.slee()方法 用try catch 抓取异常的时候 需要在 catch中调用 interrupt()方法才能中断线程
ublic class EndThreadRun {
private static class useRun implements Runnable{
@Override
public void run(){
String threadName=Thread.currentThread().getName();
while(!Thread.currentThread().isInterrupted()){
try {
Thread.sleep(100);
} catch (InterruptedException e) {
System.out.println(threadName+" is strop and interrupt is "
+Thread.currentThread().isInterrupted());
e.printStackTrace();
Thread.currentThread().interrupt();
System.out.println(threadName);
}
System.out.println(threadName+" is strop and interrupt is "
+Thread.currentThread().isInterrupted());
}
}
}
public static void main(String[] args) throws InterruptedException {
useRun useRun=new useRun();
Thread endThread=new Thread(useRun,"endThread");
endThread.start();
Thread.sleep(20);
endThread.interrupt();
}
}
知识兔