java多线程四种实现方法
Posted 惬意的小屋
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了java多线程四种实现方法相关的知识,希望对你有一定的参考价值。
package com.zrun.TestThread;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class App {
public static void main(String[] args) throws Exception, ExecutionException {
System.out.println("主线程启动:"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(new Date()));
// 方式1
// ThreadEx thread1 = new ThreadEx();
// thread1.start();
// Thread.sleep(2000);
// System.out.println("主线程执行结束:"
// + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
// .format(new Date()));
// 方式2
// Thread thread2 = new Thread(new RunableEx());
// thread2.start();
// Thread.sleep(2000);
// System.out.println("主线程执行结束:"
// + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
// .format(new Date()));
// 方式3
// Callable<Object> oneCallable = new Thread3<Object>();
// FutureTask<Object> oneTask = new FutureTask<Object>(oneCallable);
// Thread t = new Thread(oneTask);
// t.start();
// Thread.sleep(2000);
// System.out.println("主线程执行结束:"
// + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
// .format(new Date()));
// // 主线程执行的2秒钟之后,子线程只要再过3秒就结束了,从而得到子线程的结果;这里get方法会阻塞主线程
// System.out.println(oneTask.get().toString());
// 方式4
Thread4.test();
Thread.sleep(2000);
System.out.println("主线程执行结束:"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(new Date()));
}
}
// 方式1:继承Thread类
class ThreadEx extends Thread {
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("子线程执行结束:"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(new Date()));
}
}
// 方式2:实现Runnable接口
class RunableEx implements Runnable {
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("子线程执行结束:"
+ new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.format(new Date()));
}
}
// 方式3:通过Callable和FutureTask;这种方式可以拿到子线程的返回值
class Thread3<Object> implements Callable<Object> {
@Override
public Object call() throws Exception {
Thread.sleep(5000);
return (Object) ("我是子线程的返回值:" + new SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss").format(new Date()));
}
}
// 方式4:通过线程池创建线程
class Thread4 {
static int POOL_NUM = 5;
public static void test() {
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < POOL_NUM; i++) {
RunableEx thread = new RunableEx();
executorService.execute(thread);
}
// 关闭线程池
executorService.shutdown();
}
}
以上是关于java多线程四种实现方法的主要内容,如果未能解决你的问题,请参考以下文章