线程的状态以及Callable接口的使用
一、线程的状态
线程有新建状态、就绪状态,运行状态、阻塞状态,死亡状态,当线程执行完所有的代码或者interrupt中断后,就进入死亡状态,此时如果再调用start方法就会抛出异常,其中阻塞状态的线程不会释放锁。
public class TestState {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() -> {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(600L);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + i);
}
});
//查看状态
Thread.State state = thread.getState();
System.out.println( " - " + state);
thread.start(); //线程就绪
state = thread.getState();
System.out.println(" -- " + state);
while (state != Thread.State.TERMINATED){
state = thread.getState();
Thread.sleep(100L);
System.out.println(" --- " + state);
}
//执行到这里的时候 线程已经死亡,如果再start就会抛出异常
thread.start(); //IllegalThreadStateException
}
}
运行查看控制台
可以看到创建但没调用 start方法前为new新建状态,如果如果调用了start方法则进入就绪状态,此时会等待CPU的调度,当调用sleep方法时,线程就成为了阻塞状态,最后进入TERMINATED终结状态,当线程进入终结状态,如果再调用start就会抛出IllegalThreadStateException异常。
二、Callable接口的使用
创建多线程的方式通常有继承Thread类和实现Runnable接口,除了这两种还有实现Callable接口
public class MyCallable implements Callable<Object> {
@Override
public Object call() throws Exception {
for (int i = 0;i < 20;i++){
System.out.println(Thread.currentThread().getName() + " ---> " +i);
}
return UUID.randomUUID().toString();
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCallable myCallable1 = new MyCallable();
MyCallable myCallable2 = new MyCallable();
MyCallable myCallable3 = new MyCallable();
//创建执行服务
ExecutorService executorService = Executors.newFixedThreadPool(3);
Future<Object> submit1 = executorService.submit(myCallable1);
Future<Object> submit2 = executorService.submit(myCallable2);
Future<Object> submit3 = executorService.submit(myCallable3);
System.out.println(submit1.get());
System.out.println(submit2.get());
System.out.println(submit3.get());
executorService.shutdown();
}
}
实现Callable接口的好处有自定义线程的返回值类型,可抛出异常
也可以使用集合的方法并发执行
public class MyCallable2 implements Callable<Object> {
@Override
public Object call() throws Exception {
for (int i = 0;i < 20;i++){
System.out.println(Thread.currentThread().getName() + " ---> " +i);
}
return UUID.randomUUID().toString();
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
List<MyCallable2> list = new ArrayList<>();
MyCallable2 myCallable1 = new MyCallable2();
MyCallable2 myCallable2 = new MyCallable2();
MyCallable2 myCallable3 = new MyCallable2();
//创建执行服务
ExecutorService executorService = Executors.newFixedThreadPool(3);
list.add(myCallable1);
list.add(myCallable2);
list.add(myCallable3);
List<Future<Object>> futures = executorService.invokeAll(list);
for (Future<Object> future : futures) {
System.out.println(future.get());
}
executorService.shutdown();
}
}
还没有评论,来说两句吧...