第一种:继承Thread类
public class ThreadOne extends Thread {
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("输出"+i);
}
}
}
class TestOne{
public static void main(String[] args) {
ThreadOne one = new ThreadOne();
one.start();
}
}
第二种:实现Runnable接口
public class ThreadTwo implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println("输出"+i);
}
}
}
class TestTwo{
public static void main(String[] args) {
ThreadTwo two = new ThreadTwo();
Thread thread = new Thread(two);
thread.start();
}
}
第三种:实现Callable接口
public class ThreadThree implements Callable<Object> {
@Override
public Object call() throws Exception {
int value = 0;
for (int i = 1; i < 10; i++) {
value += i;
}
return value;
}
}
class TestThree{
public static void main(String[] args) {
ThreadThree threadThree = new ThreadThree();
FutureTask futureTask = new FutureTask(threadThree);
Thread thread = new Thread(futureTask);
thread.start();
try{
Object value = futureTask.get();
System.out.println("值为"+value);
}catch (Exception e){
e.printStackTrace();
}
}
}
第四种:使用线程池
public class ThreadFour {
public static void main(String[] args) {
//ExecutorService threadPool = Executors.newSingleThreadExecutor(); //创建一个单线程化的线程池,它只会用唯一的工作线程来执行任务,保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
//ScheduledExecutorService threadPool = Executors.newScheduledThreadPool(10);//创建一个定长线程池,支持定时及周期性任务执行。
//ExecutorService threadPool = Executors.newFixedThreadPool(10); //创建一个定长线程池,可控制线程最大并发数,超出的线程会在队列中等待。
ExecutorService threadPool = Executors.newCachedThreadPool(); //创建一个可缓存线程池,如果线程池长度超过处理需要,可灵活回收空闲线程,若无可回收,则新建线程。
try {
for (int i = 0; i < 10; i++) {
//使用线程池来创建线程
threadPool.execute(()->{
System.out.println(Thread.currentThread().getName()+"输出");
});
}
} catch (Exception e) {
e.printStackTrace();
} finally {
threadPool.shutdown(); //线程池使用完毕后需要关闭
}
}
}