Watch 1 Star 1 Fork 0

ConstXiong / concurrencyJava

Clone or download
006-创建启动线程.md
Copy Edit Web IDE Raw Normal History
handsomX   'concurrency' 2019-09-02
# 如何创建、启动 Java 线程?### Java 中有 4 种常见的创建线程的方式#### 一、重写 Thread 类的 run() 方法表现形式有两种:<br>1. new Thread 对象匿名重写 run() 方法``` javapackage constxiong.concurrency.a006; /**  * new Thread 对象匿名重写 run() 方法,启动线程  * @author ConstXiong  */public class TestNewThread {		public static void main(String[] args) {		//创建线程 t, 重写 run() 方法		new Thread("t") {			@Override			public void run() {				for (int i = 0; i < 3; i++) {					System.out.println("thread t > " + i);				}			}		}.start();	}}```执行结果<br>```thread t > 0thread t > 1thread t > 2```2. 继承 Thread 对象,重写 run() 方法``` javapackage constxiong.concurrency.a006;/** * 继承 Thread 类,重写 run() 方法 * @author ConstXiong */public class TestExtendsThread {		public static void main(String[] args) {		new ThreadExt().start();	}}//ThreadExt 继承 Thread,重写 run() 方法class ThreadExt extends Thread {	@Override	public void run() {		for (int i = 0; i < 3; i++) {			System.out.println("thread t > " + i);		}	}	}```执行结果<br>```thread t > 0thread t > 1thread t > 2```#### 二、实现 Runnable 接口,重写 run() 方法表现形式有两种:<br>1. new Runnable 对象,匿名重写 run() 方法``` javapackage constxiong.concurrency.a006;/** * new Runnalbe 对象匿名重写 run() 方法,启动线程 * @author ConstXiong */public class TestNewRunnable {	public static void main(String[] args) {		newRunnable();	}		public static void newRunnable() {		//创建线程 t1, 重写 run() 方法		new Thread(new Runnable() {			@Override			public void run() {				for (int i = 0; i < 3; i++) {					System.out.println("thread t1 > " + i);					try {						Thread.sleep(1000L);					} catch (InterruptedException e) {						e.printStackTrace();					}				}			}		}, "t1").start();						//创建线程 t2, lambda 表达式设置线程的执行代码		//JDK 1.8 开始支持 lambda 表达式		new Thread(() -> {			for (int i = 0; i < 3; i++) {				System.out.println("thread t2 > " + i);				try {					Thread.sleep(1000L);				} catch (InterruptedException e) {					e.printStackTrace();				}			}		}, "t2").start();	}}```执行结果<br>```thread t1 > 0thread t2 > 0thread t1 > 1thread t2 > 1thread t1 > 2thread t2 > 2```2.实现 Runnable 接口,重写 run() 方法``` javapackage constxiong.concurrency.a006;/** * 实现 Runnable 接口,重写 run() 方法 * @author ConstXiong */public class TestImplRunnable {	public static void main(String[] args) {		new Thread(new RunnableImpl()).start();	}}///RunnableImpl 实现 Runnalbe 接口,重写 run() 方法class RunnableImpl implements Runnable {	@Override	public void run() {		for (int i = 0; i < 3; i++) {			System.out.println("thread t > " + i);		}	}	}```执行结果<br>```thread t > 0thread t > 1thread t > 2```#### 三、实现 Callable 接口,使用 FutureTask 类创建线程``` javapackage constxiong.concurrency.a006;import java.util.concurrent.Callable;import java.util.concurrent.ExecutionException;import java.util.concurrent.FutureTask;/** * 实现 Callable 接口,使用 FutureTask 类创建线程 * @author ConstXiong */public class TestCreateThreadByFutureTask {	public static void main(String[] args) throws InterruptedException, ExecutionException {		//通过构造 FutureTask(Callable callable) 构造函数,创建 FutureTask,匿名实现接口 Callable 接口		FutureTask<String> ft = new FutureTask<String>(new Callable<String>() {			@Override			public String call() throws Exception {				return "ConstXiong";			}		});				//Lambda 方式实现//		FutureTask<String> ft = new FutureTask<String>(() ->  "ConstXiong");				new Thread(ft).start();		System.out.println("执行结果:" + ft.get());	}}```执行结果<br>```执行结果:ConstXiong```#### 四、使用线程池创建、启动线程``` javapackage constxiong.concurrency.a006;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;/** * 线程池的方式启动线程 * @author ConstXiong */public class TestCreateThreadByThreadPool {	public static void main(String[] args) {		// 使用工具类 Executors 创建单线程线程池		ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();		//提交执行任务		singleThreadExecutor.submit(() -> {System.out.println("单线程线程池执行任务");});		//关闭线程池		singleThreadExecutor.shutdown();	}}```执行结果<br>```单线程线程池执行任务```PS:这边只是简单的使用示例,至于 Runnable 接口和 Callable 接口的区别、线程池的使用,后面详细探索。<br>
handsomX   'concurrency' 2019-09-03
#### [查看源码](../../tree/master/code_concurrency)
handsomX   'concurrency' 2019-09-02
<br><br>
handsomX   'concurrency' 2019-09-02
[返回顶部](006-创建启动线程.md#如何创建启动-java-线程) [返回](README.md)
Java
1
https://gitee.com/ConstXiong/concurrency.git
git@gitee.com:ConstXiong/concurrency.git
ConstXiong
concurrency
concurrency
master

Help Search