一、继承Thread类
创建一个类并继承Thread类,重写run方法。
创建该类的实例,调用start方法。
public class test {
public static void main(String[] args) {
MyThread thread = new MyThread();
thread.start();
}
}
class MyThread extends Thread {
@Override
public void run() {
//要执行的代码
}
}
二、实现Runnable接口
创建一个任务类并实现Runnable接口,重写run方法。
创建该任务类的实例。
使用Thread类的有参构造传入任务类的实例。
调用Thread类的start方法。
public class test {
public static void main(String[] args) {
MyTask task = new MyTask();
Thread thread = new Thread(task);
thread.start();
}
}
class MyTask implements Runnable{
@Override
public void run() {
}
}
三、实现Callable接口
由于重写run方法无法抛出异常和返回值,如果想要抛出异常或想要返回值,可以实现Callable接口。
创建任务类实现Callable接口,重写call方法,创建任务类实例。
创建FutureTask实例,创建Thread类实例。调用start方法。
public class test {
public static void main(String[] args) {
MyTask task = new MyTask();
FutureTask futureTask = new FutureTask(task);
Thread thread = new Thread(futureTask);
thread.start();
//取得返回值
try {
futureTask.get();
} catch (InterruptedException e) {
throw new RuntimeException(e);
} catch (ExecutionException e) {
throw new RuntimeException(e);
}
}
}
class MyTask implements Callable {
@Override
public Object call() throws Exception {
//要执行的代码
return null;
}
}
实现Callable可用泛型,如果要取得call方法的返回值,可以调用FutureTask实例的get方法,需要处理异常或抛出异常。
四、使用线程池
使用线程池的好处是:
当需要线程时,不用创建新线程,提高了响应速度。用完线程后不销毁,下次还可以使用,提高了资源重用率。方便对批量线程管理。
也可自己重写自己需要的线程池。
public class test {
public static void main(String[] args) {
//newFixedThreadPool(int) 创建有指定数目线程的线程池
//newCachedThreadPool() 创建一个线程池,需要线程的时候,池中有可用线程就用,没有就新建
ExecutorService execute = Executors.newFixedThreadPool(10);
//执行任务
//execute.execute(一个实现Runnable接口的类);
//执行任务
//execute.submit(一个实现Runnable或Callable接口的类);
//关闭执行器,不再接受任务,允许剩余任务运行结束
//execute.shutdown();
//立刻关闭执行器,返回剩余任务列表List<Runnable>
//execute.showdownNow();
}
}