1.继承Thread类,重写run方法(其实Thread类本身也实现了Runnable接口)
2.实现Runnable接口,重写run方法
3.实现Callable接口,重写call方法(有返回值)
4.使用线程池(有返回值)
1.继承Thread类,重写run方法
每次创建一个新的线程,都要新建一个Thread子类的对象
启动线程,new Thread子类().start()
创建线程实际调用的是父类Thread空参的构造器
public class MyThread {
public static void main(String ards[]){
for(int i=0;i<10;i++){
new ExtendsThread().start();
}
System.out.println(Thread.currentThread().getName());
}
}
class ExtendsThread extends Thread{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
2.实现Runnable接口,重写run方法
不论创建多少个线程,只需要创建一个Runnable接口实现类的对象
启动线程,new Thread(Runnable接口实现类的对象).start()
创建线程调用的是Thread类Runable类型参数的构造器
public class MyThread {
public static void main(String ards[]){
Runnable implRunnable = new ImplRunnable();
for(int i=0;i<10;i++){
new Thread(implRunnable).start();
}
System.out.println(Thread.currentThread().getName());
}
}
class ImplRunnable implements Runnable{
private volatile int i = 0;
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"--"+ i++);
}
}
3.实现Callable接口,重写call方法(有返回值)
自定义类实现Callable接口时,必须指定泛型,该泛型即返回值的类型
每次创建一个新的线程,都要创建一个新的Callable接口的实现类、
如何启动线程?
(1)创建一个Callable接口的实现类的对象
(2)创建一个FutureTask对象,传入Callable类型的参数
public FutureTask(Callable<V> callable){……}
(3)调用Thread类重载的参数为Runnable的构造器创建Thread对象
将FutureTask作为参数传递
public class FutureTask<V> implements RunnableFuture<V>
public interface RunnableFuture<V> extends Runnable, Future<V>
如何获取返回值?
调用FutureTask类的get()方法
public class MyThread {
public static void main(String ards[]) throws InterruptedException, ExecutionException{
for(int i=0;i<10;i++){
Callable<Integer> implCallable = new ImplCallable();
FutureTask<Integer> futureTask = new FutureTask<Integer>(implCallable);
new Thread(futureTask).start();
System.out.println(Thread.currentThread().getName()+"----"+futureTask.get());
}
System.out.println(Thread.currentThread().getName());
}
}
class ImplCallable implements Callable<Integer>{
@Override
public Integer call() throws Exception {
int result = 0;
for(int i=0;i<10;i++){
result += i;
}
System.out.println(Thread.currentThread().getName());
return result;
}
}
4.线程池
Executors类
/**
*
* 线程池
* 跟数据库连接池类似
* 避免了线程的创建和销毁造成的额外开销
*
* java.util.concurrent
*
* Executor 负责现成的使用和调度的根接口
* |--ExecutorService 线程池的主要接口
* |--ThreadPoolExecutor 线程池的实现类
* |--ScheduledExecutorService 接口,负责线程的调度
* |--ScheduledThreadPoolExecutor (extends ThreadPoolExecutor implements ScheduledExecutorService)
*
*
* Executors工具类
* 提供了创建线程池的方法
*
*/
public class ThreadPool {
public static void main(String[] args){
//使用Executors工具类中的方法创建线程池
ExecutorService pool = Executors.newFixedThreadPool(5);
ThreadPoolDemo demo = new ThreadPoolDemo();
//为线程池中的线程分配任务,使用submit方法,传入的参数可以是Runnable的实现类,也可以是Callable的实现类
for(int i=1;i<=5;i++){
pool.submit(demo);
}
//关闭线程池
//shutdown : 以一种平和的方式关闭线程池,在关闭线程池之前,会等待线程池中的所有的任务都结束,不在接受新任务
//shutdownNow : 立即关闭线程池
pool.shutdown();
}
}
class ThreadPoolDemo implements Runnable{
/**多线程的共享数据*/
private int i = 0;
@Override
public void run() {
while(i<=50){
System.out.println(Thread.currentThread().getName()+"---"+ i++);
}
}
}
public class ThreadPool2 {
public static void main(String args[]){
ExecutorService executorService = Executors.newFixedThreadPool(5);
for(int i=0;i<5;i++){
Future<Integer> future = executorService.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int result = 0;
for(int i=0;i<=10;i++){
result += i;
}
return result;
}
});
try {
System.out.println(Thread.currentThread().getName()+"--"+future.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}
executorService.shutdown();
}
}
eg:带返回值
public class Testxc { //带返回值
public static void main(String[] args) throws ExecutionException, InterruptedException {
FutureTask futureTask = new FutureTask(new MyCallable("2"));
Thread thread = new Thread(futureTask);
thread.start();
if(!futureTask.isDone())
System.out.println("task has not finished!");
System.out.println(futureTask.get());
}
static class MyCallable implements Callable<Object> {
private String taskNum; //传入的参数
MyCallable( String taskNum ) {
this.taskNum = taskNum;
}
MyCallable() {
}
public Object call() throws Exception {
System.out.println(">>>" + taskNum + "任务启动");
Date dateTmp1 = new Date();
Thread.sleep(1000);
Date dateTmp2 = new Date();
long time = dateTmp2.getTime() - dateTmp1.getTime();
System.out.println(">>>" + taskNum + "任务终止");
return taskNum + "任务返回运行结果,当前任务时间【" + time + "毫秒】";
}
}
}
无返回值:
public class Test {
public static void main(String args[]){
WorkThread wtd = new WorkThread("1");
wtd.start();
}
static class WorkThread extends Thread {
// 用于停止线程
private boolean stopThread = true;
private String taskNum;
public void stopThread() {
stopThread = false;
}
/***
* @param taskNum
*/
public WorkThread(String taskNum) {
super();
this.taskNum = taskNum;
}
public void run() {
while (stopThread) {
try {
System.out.println(">>>" + taskNum + "任务启动");
Date dateTmp1 = new Date();
Thread.sleep(1000);
Date dateTmp2 = new Date();
long time = dateTmp2.getTime() - dateTmp1.getTime();
System.out.println(">>>" + taskNum + "任务终止");
} catch (Exception e) {
this.stopThread();
} finally {
this.stopThread();
}
}
}
}
}