- 继承Thread类
//通过继承Thread类创建NewThread线程
class NewThread extends Thread{
public void run(){
System.out.println("create a thread by extends Thread");
}
}
public class Main{
public static void main(String[] args) {
//实例化一个NewThread线程对象
NewThread newThread = new NewThread();
//调用start方法启动NewThread线程
newThread.start();
}
}
调用start()方法启动线程。
start()方法是要给native方法,通过在操作系统上启动一个新线程,并最终执行run方法来启动一个线程。run()方法内的代码是线程类的具体实现逻辑。
- 实现Runnable接口
//通过实现Runnable接口创建线程
class NewThread implements Runnable{
public void run() {
System.out.println("create a thread by implements Runnable");
}
}
public class Main{
public static void main(String[] args) {
// 实例化一个NewThread对象
NewThread newThread = new NewThread();
// 创建一个线程对象,并传入已经实例化好的NewThread实例
Thread thread = new Thread(newThread);
// 调用start方法启动一个线程
thread.start();
}
}
如果子类已经继承了一个类,就无法再直接继承Thread类,此时可以通过实现runnable接口创建线程。
过程:通过实现runnable接口创建线程,实例化线程对象newThread ,创建Thread类实例thread 并传入已经实例化好的newThread实例,调用线程的start方法启动线程。
- 通过ExecutorService和Callable实现有返回值的线程
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
//通过实现callable接口创建NewThread线程
class NewThread implements Callable<String> {
private String name;
public NewThread(String name){
//通过构造函数为线程传递参数,以定义线程名称
this.name = name;
}
@Override
public String call() throws Exception {
// 线程实现逻辑
return name;
}
}
public class Main{
public static void main(String[] args) throws ExecutionException, InterruptedException {
// 创建固定大小为5的线程池
ExecutorService pool = Executors.newFixedThreadPool(5);
// 创建多个有返回值的任务列表list
List<Future> list = new ArrayList<Future>();
for(int i = 0;i < 5;i++){
// 创建有返回值的线程实例
Callable c = new NewThread(i + "");
// 提交线程,获取Future对象并保存到Future List中
Future future = pool.submit(c);
System.out.println("submit a callable thread:" + i);
list.add(future);
}
// 关闭线程池,等待线程执行结束
pool.shutdown();
// 遍历所有线程的运行结果
for (Future future:list){
// 从future对象上获取任务的返回值
System.out.println("get the result from callable thread:"+ future.get().toString());
}
}
}
在主线程中开启多个线程并发执行一个任务,然后收集各个线程执行返回的结果并将最终结果汇总起来,需要用到Callable接口。
- 基于线程池
在每次需要时创建线程,运行结束后销毁时非常浪费资源的。可以使用线程池来创建线程。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main{
public static void main(String[] args){
// 创建固定大小为10的线程池
ExecutorService pool = Executors.newFixedThreadPool(10);
for(int i = 0;i < 10;i++){
pool.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() +" "+ "is running");
}
});
}
}
}
参考资料
《offer来了(原理篇)》

被折叠的 条评论
为什么被折叠?



