一、继承Thread类
Thread 类本质上是实现了Runnable 接口的一个实例,代表一个线程的实例。启动线程的唯一方法就是通过Thread 类的start()实例方法。start()方法是一个native 方法,它将启动一个新线程,并执行run()方法
public class TestThread extends Thread {
@Override
public void run() {
System.out.println("MyThread.run()");
}
public static void main(String[] arg) {
TestThread myThread = new TestThread();
myThread.start();
}
}
二、实现Runnable接口
如果自己的类已经extends 另一个类,就无法直接extends Thread,此时,可以实现一个Runnable 接口。
public class TestThread implements Runnable {
public static void main(String[] args) {
TestThread myThread = new TestThread();
Thread thread = new Thread(myThread);
thread.start();
}
@Override
public void run() {
System.out.println("TestThread");
}
}
三、ExecutorService、Callable、Future 有返回值的线程
有返回值的任务必须实现Callable 接口,类似的,无返回值的任务必须Runnable 接口。执行Callable 任务后,可以获取一个Future 的对象,在该对象上调用get 就可以获取到Callable 任务返回的Object 了,再结合线程池接口ExecutorService 就可以实现有返回结果的多线程了。
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class TestThread implements Callable<String> {
private String name;
TestThread(String name) {
this.name = name;
}
@Override
public String call() throws Exception {
Thread.sleep(30);
System.out.println(this.name+":callable方法执行了");
return this.name;
}
public static void main(String[] args) throws InterruptedException, ExecutionException {
// 1.创建一个线程池
int taskSize = 10;
ExecutorService executorService = Executors.newFixedThreadPool(taskSize);
List<Future<String>> list = new ArrayList<Future<String>>();
for (int i = 0; i < taskSize; i++) {
// 创建多个callable对象
TestThread callable = new TestThread("callable" + i);
// 执行任务并把返回的Future对象添加到list中
Future<String> f = executorService.submit(callable);
list.add(f);
}
// 关闭线程池
executorService.shutdown();
// 获取所有并发任务的运行结果
for (Future<String> f : list) {
// 从Future 对象上获取任务的返回值,并输出到控制台
System.out.println("res:" + f.get());
}
}
}
基于线程池的方式
线程和数据库连接这些资源都是非常宝贵的资源。那么每次需要的时候创建,不需要的时候销
毁,是非常浪费资源的。那么我们就可以使用缓存的策略,也就是使用线程池。
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestThread {
public static void main(String[] args) {
ExecutorService executorService = Executors.newFixedThreadPool(10);
while (true) {
executorService.execute(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
});
}
}
}