Java实现多线程的方式有4种分别是继承Thread类,实现Runnable,Callable接口和通过线程池提交线程任务。其中实现Callable接口的方式可以获取返回值。
1. 继承Thread类
通过继承Thread类,重写run方法
public class ThreadExtends extends Thread {
@Override
public void run() {
System.out.println("通过继承Thread类实现Java多线程,当前线程:"
+"["+Thread.currentThread().getName()+"]");
}
public static void main(String[] args) {
System.out.println("当前线程:"+"["+Thread.currentThread().getName()+"]");
new ThreadExtends().start();
}
}
2. 实现Runnable接口
通过实现Runnable接口
public class RunnableImpl implements Runnable {
@Override
public void run() {
System.out.println("通过实现Runnable接口实现Java多线程,当前线程:"
+ "[" + Thread.currentThread().getName() + "]");
}
public static void main(String[] args) {
System.out.println("当前线程:"+"["+Thread.currentThread().getName()+"]");
new Thread(new RunnableImpl()).start();
}
}
3. 实现Callable接口
通过实现Callable接口,使用FutureTask包装器实现Java的多线程。可以通过get方法获取返回值。
public class CallableImpl implements Callable<String> {
@Override
public String call() throws Exception {
System.out.println("通过实现Callable接口实现Java多线程,当前线程:"
+ "[" + Thread.currentThread().getName() + "]");
return "通过实现Callable接口实现Java多线程";
}
public static void main(String[] args) {
Callable<String> task = new CallableImpl();
FutureTask<String> futureTask = new FutureTask<>(task);
new Thread(futureTask).start();
System.out.println("当前线程:"+"["+Thread.currentThread().getName()+"]");
try {
String result = futureTask.get();
System.out.println("result = " + result);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
4. 通过线程池创建多线程
使用线程池,提交任务,实现java多线程。
public void threadPool() {
ExecutorService service = Executors.newFixedThreadPool(4);
//1. RunnableTask
Runnable runTask = () ->
System.out.println("当前线程:" + "[" +
Thread.currentThread().getName() + "]");
service.submit(runTask);
//2.CallableTask: 通过实现Callable接口创建的线程任务
Callable<String> callTask = () -> {
System.out.println("当前线程:" + "[" +
Thread.currentThread().getName() + "]");
return Thread.currentThread().getName();
};
service.submit(callTask);
//3. 通过FutureTask 封装器封装Callable实现类提交任务
FutureTask<String> futureTask = new FutureTask<>(callTask);
service.submit(futureTask);
//4. 提交Thread任务
service.submit(new Thread(runTask));
service.shutdown();
}
标签:Java,currentThread,Thread,实现,Callable,线程,多线程,public
From: https://www.cnblogs.com/pangcode/p/16771860.html