1.继承Thread类创建线程
线程类
public class MyThread extends Thread {
@Override
public void run() {
for (int i = 0; i <= 10; i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i);
}
}
}
测试代码
MyThread thread=new MyThread();
thread.start();
System.out.println("123");
2.实现Runable接口创建线程
线程类
public class MyRunable implements Runnable {
@Override
public void run() {
for (int i = 0; i <= 10; i++) {
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i);
}
}
}
测试代码
Thread runable=new Thread(new MyRunable());
runable.start();
System.out.println("456");
3.使用线程池实现多线程
ExecutorService、Callable、Future对象都是属于Executor框架中的功能类
Executors类,提供工厂方法用于创建线程池,返回的线程池都实现了ExecutorService接口
创建有返回值的线程 必须实现Callable<V>接口,无返回值的实现Runable接口
// 创建固定数目线程的线程池
ExecutorService executorService = Executors.newFixedThreadPool(int poolSize);
// 创建一个可缓存的线程池
ExecutorService executorService = Executors.newCachedThreadPool();
// 创建一个单线程化的线程池
ExecutorService executorService = Executors.newSingleThreadExecutor();
// 创建一个支持定时及周期性的任务执行的线程池
ExecutorService executorService = Executors.newScheduledThreadPool(int corePoolSize);
线程类
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
public class MyExecutorCallable implements Callable<Object> {
private List<String> names;
public MyExecutorCallable() {
}
@Override
public Object call() throws Exception {
names = new ArrayList<>();
for (int i = 0; i <= 5; i++) {
names.add("Name" + i + "\n");
}
return names;
}
}
测试代码
// 创建固定数目线程线的程池
ExecutorService executorService = Executors.newFixedThreadPool(10);
// 创建多个有返回值的任务
List<Future> futures = new ArrayList<>();
for (int i = 0; i < 5; i++) {
Callable callable = new MyExecutorCallable ();
// 执行任务并获取返回值
Future future = executorService.submit(callable);
futures.add(future);
}
// 关闭线程池
executorService.shutdown();
// 输出返回值
for (Future future : futures) {
System.out.println(future.get().toString() + "\n");
}