java线程三种创建方式_创建线程的三种方式

一、继承Thread类java中类是单继承的,继承了该类就无法继承其他类,增加了代码的耦合度,现在提倡的是面向接口编程。二、实现Runnable接口相比与方式一,使用实现接口来实现,降低了程序间的耦合度,缺点是没有返回值。三、实现Callable接口,将Callable实例传给FutureTask(FutureTask实现了RunnableFuture接口,RunnableFuture继承了Runnable接口)和方式二一样也是通过实现接口来创建线程,不同的是可以有返回值。代码:

package com.shamgod.thread;

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;

import java.util.concurrent.FutureTask;

/**

* 创建线程的三种方式

* @author ShammGod

*

*/

public class TestThread {

public static void main(String[] args) throws InterruptedException, ExecutionException {

//继承Thread类

Thread t1 = new Thread1();

t1.start();

//实现Runnable接口,将该实例作为参数创建Thread对象

Runnable runnable = new Thread2();

Thread t2 = new Thread(runnable);

t2.start();

//实现Callable接口,将该实例作为参数创建FutureTask对象,将FutureTask对象作为参数创建Thread对象

Callable callable = new Thread3();

FutureTask futureTask = new FutureTask<>(callable);

Thread t3 = new Thread(futureTask);

t3.start();

futureTask.get();//call方法的返回值

//实现Callable接口,将该实例传给线程池的submit方法启动线程

ExecutorService threadPool = Executors.newCachedThreadPool();

Callable task = new Thread3();

Future future = threadPool.submit(task);

threadPool.shutdown();

future.get();//call方法的返回值

}

}

/**

* 1、继承Thread

* @author ShammGod

*

*/

class Thread1 extends Thread{

@Override

public void run() {

System.out.println("我是继承Thread创建的线程:" + Thread.currentThread().getName());

}

}

/**

* 2、实现Runnable接口

* @author ShammGod

*

*/

class Thread2 implements Runnable{

@Override

public void run() {

// TODO Auto-generated method stub

System.out.println("我是实现Runnable接口创建的线程:"+Thread.currentThread().getName());

}

}

/**

* 3、实现Callable接口

* @author ShammGod

*

*/

class Thread3 implements Callable{

@Override

public String call() throws Exception {

System.out.println("我是实现Callable接口创建的线程:"+Thread.currentThread().getName());

return "返回值";

}

}

若有不正之处请多多谅解,并欢迎批评指正。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值