创建线程的4种方式
一、继承Thread类
public class Main {
public static void main(String[] args) {
// // 1.创建Thread子类对象
// ThreadDemo threadDemo = new ThreadDemo();
// // 2.启动线程
// threadDemo.start();
// 使用内部类方式
new Thread() {
@Override
public void run() {
System.out.println("继承Thread来创建线程:" + Thread.currentThread().getName());
}
}.start();
}
static class ThreadDemo extends Thread {
@Override
public void run() {
System.out.println("继承Thread来创建线程:" + Thread.currentThread().getName());
}
}
}
二、实现Runnable接口
public class Main {
public static void main(String[] args) {
// // 1.创建Runnable实现类对象
// ThreadDemo threadDemo = new ThreadDemo();
// // 2.创建Thread对象
// Thread thread = new Thread(threadDemo);
// // 3.启动线程
// thread.start();
// 使用内部类方式
new Thread(new Runnable() {
public void run() {
System.out.println("实现Runnable来创建线程:" + Thread.currentThread().getName());
}
}).start();
}
static class ThreadDemo implements Runnable {
public void run() {
System.out.println("实现Runnable来创建线程:" + Thread.currentThread().getName());
}
}
}
三、实现Callable接口
public class Main {
public static void main(String[] args) {
// 1.创建Callable实现对象
ThreadDemo threadDemo = new ThreadDemo();
// 2.创建FutureTask对象
FutureTask<String> futureTask = new FutureTask<String>(threadDemo);
// 3.创建Thread对象
Thread thread = new Thread(futureTask);
// 4.启动线程
thread.start();
// 获取线程返回值
try {
String callReturn = futureTask.get(); // 会一直等待线程结束获取其返回值,如果线程被中断会抛异常
System.out.println(callReturn);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
static class ThreadDemo implements Callable<String> {
public String call() throws Exception {
return "实现Callable接口创建线程:" + Thread.currentThread().getName();
}
}
}
四、使用Executor框架来创建线程池
public class Main {
public static void main(String[] args) {
// 方式1.Executors创建单个线程池
// ExecutorService pool = Executors.newSingleThreadExecutor();
// pool.execute(new Runnable() {
// public void run() {
// System.out.println("线程池创建线程:" + Thread.currentThread().getName());
// }
// });
// pool.shutdown();
// 方式2.Executors创建固定数量线程池
ExecutorService pool = Executors.newFixedThreadPool(5);
List<Future<String>> futures = new ArrayList<Future<String>>(); // 存储结果集
for(int i = 0; i < 5; i++) {
Future<String> submit = pool.submit(new Callable<String>() {
public String call() throws Exception {
return "线程池创建线程:" + Thread.currentThread().getName();
}
});
futures.add(submit);
}
System.out.println("开始获取任务结果");
for(Future<String> future : futures) {
try {
// 使用get(long timeout, TimeUnit unit)指定获取结果超时时间
System.out.println(future.get(1000, TimeUnit.SECONDS));
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} catch (TimeoutException e) {
e.printStackTrace();
}
}
System.out.println("获取任务结果结束");
// 关闭线程池
pool.shutdown();
}
}
执行结果:
开始获取任务结果
线程池创建线程:pool-1-thread-1
线程池创建线程:pool-1-thread-2
线程池创建线程:pool-1-thread-3
线程池创建线程:pool-1-thread-4
线程池创建线程:pool-1-thread-5
获取任务结果结束