JAVA 线程实现/创建方式

一、继承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();
					}
				}
			});
		}
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值