一、初始化线程
方式一:继承Thread
public class Thread01 extends Thread {
@Override
public void run() {
System.out.println("当前线程:" + Thread.currentThread().getName());
int i = 10 / 2;
System.out.println("运行结果:" + i);
}
}
public static void main(String[] args) {
Thread01 thread01 = new Thread01();
thread01.start();
System.out.println("main。。。end。。。");
}
main。。。end。。。
当前线程:Thread-0
运行结果:5
方式二:实现Runnable
public static class Runable01 implements Runnable {
@Override
public void run() {
System.out.println("当前线程:" + Thread.currentThread().getName());
int i = 10 / 2;
System.out.println("运行结果:" + i);
}
}
public static void main(String[] args) {
Runable01 runable01 = new Runable01();
new Thread(runable01).start();
System.out.println("main。。。end。。。");
}
当前线程:Thread-0
运行结果:5
main。。。end。。。
方式三:实现Callable<T>
public static class Callable01 implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("当前线程:" + Thread.currentThread().getName());
int i = 10 / 2;
System.out.println("运行结果:" + i);
return i;
}
}
public static void main(String[] args) throws ExecutionException, InterruptedException {
Callable01 callable01 = new Callable01();
FutureTask<Integer> task = new FutureTask<>(callable01);
new Thread(task).start();
// 等待整个线程执行完成,获取返回结果
Integer integer = task.get();
System.out.println("main。。。end。。。" + integer);
}
当前线程:Thread-0
运行结果:5
main。。。end。。。5
方式四:线程池
// 定义线程池
public static ExecutorService executor = Executors.newFixedThreadPool(10);
public static void main(String[] args) throws ExecutionException, InterruptedException {
executor.execute(new Runable01());
System.out.println("main。。。end。。。");
}
当前线程:pool-1-thread-1
运行结果:5
main。。。end。。。
- 小结
- 1、方式一和方式二:主线程无法获取线程的运算结果。
- 2、方式三:主进程可以获取线程的运算结果,但是不利于控制服务器中的线程资源,可能导致服务器资源耗尽。
- 3、方式四:通过线程池性能稳定,也可以获取执行结果,并捕获异常。
网友评论