Java基础面试题(8)----线程实现的四种方式

这次会介绍关于线程的一些基本知识,不做问题分类,分为知识点

线程的实现方式

  • 方式1,继承Thread类
    由于Java语言单继承特性,导致这种方式不推荐使用,代码如下
//实现线程的类
public class MyThread extends Thread{
    @Override
    public void run() {

        System.out.println(this.getName()+"继承Thread类实现");
    }
}

//启动线程的类
public class ThreadTest {

    public static void main(String[] args) {

        MyThread myThread01 = new MyThread();

        myThread01.setName("线程1---");

        myThread01.start();
    }
}

  • 方式2.实现Runnable接口
//创建一个类,实现Runnable
public class MyThread2 implements Runnable {

    @Override
    public void run() {
        System.out.println("实现Runnable接口");
    }
}


//测试代码
public class ThreadTest {

    public static void main(String[] args)  {
       
       //首先创建一个Thread类,在Thread类的构造方法中,允许传入一个Runnable接口的实现类
        Thread thread2 = new Thread(new MyThread2());
        

        thread2.start();

    }
}

  • 实现方式3,实现Callable接口
    通过FutureTask包装器来创建Thread线程,可以使任务具有返回值,返回结果的线程是在JDK1.5中引入的新特征,有了这种特征就不需要再为了得到返回值而大费周折了。而且自己实现了也可能漏洞百出。这里使用Futrue对象的get()方法获得线程的返回结果。
    注意:get方法是阻塞的,即:线程无返回结果,get方法会一直等待。
//实现Callable接口
import java.util.concurrent.Callable;

public class MyThread3 implements Callable<Integer>  {


    @Override

    public Integer call() throws Exception {


        System.out.println(Thread.currentThread().getName()+"实现Callable接口");

        return 0;
    }

}


//测试启动
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

public class ThreadTest {

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


        MyThread3 myThread3 = new MyThread3();

        //通过futureTask包装器传入一个类
        FutureTask<Integer> task = new FutureTask<>(myThread3);

        Thread thread3 = new Thread(task);


        thread3.start();
        //获取线程的返回结果
        Integer integer = task.get();
     
        System.out.println(integer+"线程的返回结果");
    }
}


  • 实现方式4
    上述代码中Executors类,提供了一系列工厂方法用于创建线程池,返回的线程池都实现了ExecutorService接口。
//线程的实现类
import java.util.Date;
import java.util.concurrent.Callable;

public class MyThread04 implements Callable {

    private String taskNum;

    public MyThread04(String taskNum){

        this.taskNum=taskNum;
    }


    @Override
    public Object call() throws Exception {
        //开始时间
        Date dateBegin = new Date();
        Thread.sleep(1000);
        //结束时间
        Date dateEnd = new Date();
        System.out.println(taskNum+"------------任务终止");

        return taskNum +"任务执行共使用了"+(dateEnd.getTime()-dateBegin.getTime());
    }
}


//线程执行的测试类
import java.util.ArrayList;
import java.util.Date;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class ThreadTest02 {


    public static void main(String[] args) throws ExecutionException, InterruptedException {
        System.out.println("--------程序开始运行-------");


        int taskSize=5;

        //创建一个线程池
        ExecutorService pool = Executors.newFixedThreadPool(taskSize);

        //创建有返回值的任务
        ArrayList<Future> futureArrayList = new ArrayList<>();
        for (int i = 0; i < taskSize; i++) {

            //得到一个包装器
            MyThread04 myThread04 = new MyThread04(i + "");
            Future future = pool.submit(myThread04);

            futureArrayList.add(future);
        }

        //释放资源
        pool.shutdown();


        //获取任务的返回值,执行时间
        for (Future future : futureArrayList) {

            System.out.println(future.get());
        }
    }
}



  • 创建固定数量大小的线程池
    public static ExecutorService newFixedThreadPool(int nThreads)

  • 创建一个可以缓存的线程池
    public static ExecutorService newCachedThreadPool();
    创建一个可以缓存的线程池,调用execute 将会重复使用以前的构造的线程(如果线程可用)。如果没有可用的线程,则会创建一个新的线程并添加到线程池。终止并从缓存中移除那些60S没有被使用的线程。

  • public static EcecutorService newSingleThreadPool()
    创建一个单线程化的Executor。

  • public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize)
    创建一个支持定时及周期性的任务执行的线程池,多数情况下可用来替代Timer类。

  • ExecutoreService提供了submit()方法,传递一个Callable,或Runnable,返回Future。如果Executor后台线程池还没有完成Callable的计算,这调用返回Future对象的get()方法,会阻塞直到计算完成。


这里我们实现线程和执行线程的四种方式就介绍完了。

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值