JAVA实现多线程的方法

    xiaoxiao2021-03-25  150

    并发编程使我们可以将程序划分为多个分离的、独立运行的任务。通过多线程机制,这些独立任务中的没一个都将由执行线程来驱动。要搞清这些,就先搞清什么叫线程?所谓线程,就是进程中的一个单一的顺序控制流。

    多线程的实现一般有三种方法:

    1、继承Thread类,重写run()方法。

    Thread本质上是Runnable接口的一个实例,它代表一个线程的实例,并且启动线程的唯一方法就是通过Thread类的start()方法。

    class MyThread extends Thread{ public void run(){ System.out.println("hello world"); //线程的函数体 } } public class Test{ public static void main(String[] args){ MyThread myThread=new MyThread(); thread.start(); //开启线程 } }

    其中,start()方法是一个native方法,它将启动一个新的线程,并执行run()方法。需要注意的是,调用start()方法后并不是立即执行多线程代码,而是是的该线程变为可运行态,至于什么时候运行,由操作系统决定。

    2、实现Runnable接口,实现run()方法。

    主要步骤:(1)、自定义类并实现Runnable接口,实现run()方法。(2)、创建Thread对象,将自定义类的对象作为参数实例化Thread对象。(3)、调用Thread的start方法。

    class MyThread implements Runnable{ //创建线程类 public void run(){ System.out.println("Hello World"); } } public class Test{ public static void main(String[] args){ MyThread thread=new MyThread(); Thread t=new Thread(thread); //自定义实现Runnable对象作为参数实例化Thread对象 t.start(); //开启线程 } }

    3、使用Executor

    Executor是JAVA SE5提供的为你管理Thread对象的执行器,主要目的是为了简化并发编程,并且可以返回结果。Executor,Callable、Future都属于Executors框架中功能类。Executor在客户端和任务执行之间提供了一个间接层,与客户端直接执行任务不同,这个中介将执行任务。而在JAVA语言中,Excutor是一个接口,如果需要执行器服务,则需要借助Executors这个类(有点类似于Collection与Collections的关系)。这种方式来实现线程需要首先实现Callable接口,重写call()方法,然后调用Executors的新建线程池的方法获取ExecutorService,通过ExecutorService来获取Future对象,然后通过Future对象的get方法就可以获取Callable返回的Object了。

    class MyExecutors implements Callable<String>{ //实现Callable接口 @Override public String call() throws Exception { //实现call方法,返回String类型。 // TODO Auto-generated method stub return "Hello World"; } } public class TestExecutors { public static void main(String[] args) throws InterruptedException, ExecutionException{ // 通过Executors类中的方法来获取一个线程池,提供执行器(Executor)服务 ExecutorService exec=Executors.newCachedThreadPool(); //submit()方法会产生Future对象,它用Callable返回结果的特定类型进行参数化。 Future<String> future=exec.submit(new MyExecutors()); //通过future对象的get方法来获取结果。 System.out.println(future.get()); } }

    转载请注明原文地址: https://ju.6miu.com/read-18303.html

    最新回复(0)