线程的状态转换与线程使用的三种方法
2018-02-23 本文已影响47人
9dfaf364d57f
1、线程6种状态

2、实现多线程的3种方法
(1)继承Thread类,重写run()方法
public class TestThread extends Thread {
@Override
public void run() {
System.out.println("Hello World");
}
public static void main(String []args){
TestThread testThread = new TestThread();
testThread.start();
}
}
(2)实现Runnable接口,重写run()方法
public class TestRunnable implements Runnable {
@Override
public void run() {
System.out.println("Hello World");
}
public static void main(String []args){
TestRunnable testRunnable = new TestRunnable();
Thread thread = new Thread(testRunnable);
thread.start();
}
}
需要通过Thread后进行start。
(3)实现Callable接口,重写call()方法
public class TestCallable {
public static class MyTestCallable implements Callable{
@Override
public String call() throws Exception {
return "Hello World";
}
}
public static void main(String[] args){
MyTestCallable myTestCallable = new MyTestCallable();
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future future = executorService.submit(myTestCallable);
try {
System.out.println(future.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
Tip:
(1)callable的全路径是java.util.concurrent.Callable
(2
Callable接口是属于Executor框架中的功能类,与Runnable接口功能类似,但比Runnable更加强大,主要为:
(1)线程执行完成后返回值
(2)Callable的call方法可以抛出异常
(3)Callable可以获取到一个Future对象,线程是异步的,可以通过Future获取异步计算结果。
3、线程中断
(1)interrupt() 向当前调用者线程发出中断信号
(2)isinterrupted() 查看当前中断信号是true还是false
(3)interrupted() 是静态方法,查看当前中断信号是true还是false并且清除中断信号,顾名思义interrupted为已经处理中断信号。
/**
* 三个方法的使用
*/
Thread curr = Thread.currentThread();
//设置中断
curr.interrupt();
//先获取当前清除后,获取当前中断信号
Thread.interrupted());
//获取中断信号状态
curr.isInterrupted());
三个方法的更加详细讲述请参考:http://blog.csdn.net/qpc908694753/article/details/61414495