第一种:继承Thread类
表示一个线程的实例,启动线程的唯一方法就是通过Thread类的start()方法。
start()方法是一个native(本地)方法,它将启动一个新线程,并执行run()方法(Thread类中提供的run()方法是一个空方法)。
run()方法只要有类继承了Thread类,就必须要重写该方法。
当start()方法调用后并不是立即执行多线程代码,而是使得该线程变为可运行态(Runable),什么时候运行多线程是由操作系统决定的。
步骤:
1. 创建一个继承与Thread类的子类
2. 重写Thread类的run()方法 --> 将此线程执行的操作声明在run()中
3. 创建Thread类的子类对象 --> 主线程中做
4. 通过此对象调用start()方法 start()的作用:1、启动当前线程; 2、调用当前线程的run()方法
//1. 创建一个继承与Thread类的子类
class MyThread extend Thread{
//2. 重写Thread类的run()方法
public void run(){
System.out.println("线程的方法体")
}
}
public class Test{
public static void main(String[] args){
3. 创建Thread类的子类对象
MyTread thread = new MyThread();
//4. 通过此对象调用start()方法 ,启动当前线程
thread.start();
}
}
第二种:实现Runnable接口
1. 创建一个实现了Runnable接口的类
2. 实现类去实现Runnable中的抽象方法:run()
3. 创建实现类的对象
4. 将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
5. 通过Thread类的对象去调用start方法
//1. 创建一个实现了Runnable接口的类
class MyThread implements Runnable{
//2. 实现类去实现Runnable中的抽象方法:run()
public void run(){
System.out.println("线程的方法体")
}
}
public class Test{
public static void main(String[] args){
//3. 创建实现类的对象
MyTread thread = new MyThread();
//4. 将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象
Thread t = new Thread(thread);
// 5. 通过Thread类的对象去调用start方法
t.start();
}
}
第三种:实现Callable接口
Callable对象实际是属于Executor框架中的功能类,Callable接口与Runable接口类型,只是比Runable提供了更强大的功能:
1)Callable可以在任务结束后提供一个返回值,Runnable无法提供这个功能。
2)可以抛异常
3)支持泛型
1. 创建一个实现Callable的实现类
2.实现call方法,将此线程需要执行的操作声明在call()中
3. 创建Callable接口实现类的对象
4、将此Callable接口实现类的对象作为实参传递到FutureTask构造器中,创建FutureTask对象
5. 将FutureTask的对象作为参数传递懂Thread类的构造器中,创建Thread对象,并调用start()
//1. 创建一个实现Callable的实现类
class NumThread implements Callable{
2.实现call方法,将此线程需要执行的操作声明在call()中
@Override
public Object call() throw Exception{
int sum = 0;
System.out.println("线程的方法体")
return sum;
}
public class ThreadNew{
public static void main(String[] args){
//3. 创建Callable接口实现类的对象
NumThread numThread = new NumThread();
//4、将此Callable接口实现类的对象作为实参传递到FutureTask构造器中,创建FutureTask对象
FutureTask futureTask = new FutureTask(numThread);
//5. 将FutureTask的对象作为参数传递懂Thread类的构造器中,创建Thread对象,并调用start()
new Thread(futureTask).start();
}
}
第四种:使用线程池
JDK5.0 提供了线程池相关API:ExecuteService 和 Executors
ExecuteService: 真正的线程池接口。常见子类:ThreadPoolExecuor
void execute(Runnable command):执行任务/命令,没有返回值,一般用来执行Runnable
<T>Future<T> submit(Callable<T> task): 执行任务,有返回值,一般用来执行Callable
void shutdown(): 关闭连接池
Executors: 工具类,线程池的工厂类,用于创建并返回不同类型的线程池
Executors.newCachedThreadPool():创建一个可根据需要创建新线程的线程池
Executors.newFlxedThreadPool(n):创建一个可重用固定线程数的线程池
Executors.newSingleThreadExecutor() :创建一个只有一个线程的线程池
Executors.newScheduledThreadPool(n):创建一个线程池,它可安排在给定延迟后运行命令或者定期地执行。