1)、继承Thread
2)、实现Runnable接口
3)、实现Callable接口+ FutureTask (可以拿到返回结果,可以处理异常)-JDK1.5以后添加的
4)、线程池
方式1和方式2:主进程无法获取线程的运算结果。不适合当前场景
方式3:主进程可以获取线程的运算结果,但是不利于控制服务器中的线程资源。可以导致服务器资源耗尽。
上代码看看写法
继承Thread
/**
* @author TAO
* @description: 线程创建测试类
* @date 2020/7/22 22:56
*/
public class TestThread {
public static void main(String[] args) {
System.out.println("程序.........启动了");
//继承Thread
Thread1 thread1=new Thread1();
thread1.start();//启动继承Thread类型线程
System.out.println("程序.........结束了");
}
//继承Thread
public static class Thread1 extends Thread {
@Override
public void run() {
System.out.println("进入当前线程");
System.out.println("当前线程ID " + Thread.currentThread().getId());
System.out.println("结束当前线程");
}
}
}
实现Runnable接口
/**
* @author TAO
* @description: 线程创建测试类
* @date 2020/7/22 22:56
*/
public class TestThread {
public static void main(String[] args) {
System.out.println("程序.........启动了");
//实现Runnable接口
Runable1 runable1=new Runable1();
new Thread(runable1).start();
System.out.println("程序.........结束了");
}
//实现Runnable接口
public static class Runable1 implements Runnable {
@Override
public void run() {
System.out.println("进入当前线程");
System.out.println("当前线程ID " + Thread.currentThread().getId());
System.out.println("结束当前线程");
}
}
}
实现Callable接口
/**
* @author TAO
* @description: 线程创建测试类
* @date 2020/7/22 22:56
*/
public class TestThread {
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("程序.........启动了");
FutureTask<Integer> futureTask = new FutureTask<>(new Callable1());
new Thread(futureTask).start();
Integer res=futureTask.get();//这里是阻塞等待整个Callable1线程执行完成,并获取返回结果
System.out.println("得到返回结果"+res);
System.out.println("程序.........结束了");
}
public static class Callable1 implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("进入当前线程");
System.out.println("当前线程ID " + Thread.currentThread().getId());
System.out.println("结束当前线程");
return 111;
}
}
}
线程池
/**
* @author TAO
* @description: 线程创建测试类
* @date 2020/7/22 22:56
*/
public class TestThread {
public static ExecutorService service = Executors.newFixedThreadPool(10);//一般系统只维护一个线程池,不过也看业务需要咯
public static void main(String[] args) throws ExecutionException, InterruptedException {
System.out.println("程序.........启动了");
service.execute(new Runable1());
System.out.println("程序.........结束了");
}
public static class Runable1 implements Runnable {
@Override
public void run() {
System.out.println("进入当前线程");
System.out.println("当前线程ID " + Thread.currentThread().getId());
System.out.println("结束当前线程");
}
}
}