多线程创建的三种方式

    xiaoxiao2021-03-26  23

    方式一:创建Thread的子类

    1、创建Thread子类的一个实例并重写run方法,run方法会在调用start()方法之后被执行,创建并运行上述Thread子类

    class Mythread extends Thread{     public void run(){         System.out.println(Thread.currentThread().getId()+"  "+"hello 2017");     } } public class Test1 {     public static void main(String[] args) throws InterruptedException {         //开启2个线程         Mythread my1=new Mythread();         Mythread my2=new Mythread();         my1.start();         my2.start();                  //开启100个线程         for(int i=0;i<100;i++){             new Mythread().start();             Thread.sleep(1);         }         System.out.println("I am the mianThrad");     } }2、创建一个Thread的匿名子类

    //匿名内部类创建一个线程 Thread t1=new Thread(){ public void run(){ System.out.println("hello china"); } }; t1.start(); //匿名子类实现 -- 创建100个线程: Thread th[] = new Thread[100]; for (int i = 0; i < 100; i++) { th[i]=new Thread(){ public void run(){ System.out.println(Thread.currentThread().getId()+" Thread Running"); } }; th[i].start(); th[i].join(); } System.out.println("I am mianThrad"); 3、lambda实现

            // lambda创建一个线程         Thread myth = new Thread(() -> {             System.out.println("2017");         });         myth.start();                  // 方法三:lambda实现 -- 创建100个线程:         Thread th[] = new Thread[100];         for (int i = 0; i < 100; i++) {             final int idata = i; // 必须是final类型的             th[i] = new Thread(() -> {                 System.out.println("lambda  " + idata);             });             th[i].start();             th[i].join();         }         System.out.println("I am mianThrad");

    方式二: 实现Runnable接口

    1、实现了Java.lang.Runnable接口的类,为了使线程能够执行run()方法,需要在Thread类的构造函数中传入 MyRunnable的实例对象

    class MyRunnable implements Runnable{ @Override public void run() { System.out.println(Thread.currentThread().getName()); } } public class Test2 { public static void main(String[] args) throws InterruptedException { //开启2个线程 Thread t1=new Thread(new MyRunnable(),"A"); Thread t2=new Thread(new MyRunnable(),"B"); t1.start(); t2.start(); //开启100个线程 for (int i = 0; i < 100; ++i) { new Thread(new MyThreads()).start(); Thread.sleep(1); } } }2、也可以创建一个实现了Runnable接口的匿名类

    //匿名内部类实现 Runnable r1=new Runnable(){ @Override public void run() { System.out.println(Thread.currentThread().getId()+" hello 2017"); } }; //创建一个线程 Thread t3=new Thread(r1); t3.start(); //创建100个线程 Thread []ths=new Thread[100]; for(int i=0;i<100;i++){ ths[i]=new Thread(r1); ths[i].start(); ths[i].join(); }

    方式三:

    有返回值的线程

    使用ExecutorService、Callable、Future实现有返回结果的多线程 ExecutorService、Callable、Future这个对象实际上都是属于Executor框架中的功能类。 可返回值的任务必须实现Callable接口,类似的,无返回值的任务必须Runnable接口。执行Callable任务后,可以获取一个Future的对象,在该对象上调用get就可以获取到Callable任务返回的Object了,再结合线程池接口ExecutorService就可以实现传说中有返回结果的多线程了。下面提供了一个完整的有返回结果的多线程测试例子。

    package com.zgf.test; import java.util.concurrent.*; import java.util.Date; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.LinkedList; import java.util.List; import java.util.Random; import java.util.Set; import java.util.ArrayList; /** * 有返回值的线程 */ class MyCallable implements Callable<Object> { private String taskNum; MyCallable(String taskNum) { this.taskNum = taskNum; } public Object call() throws Exception { System.out.println(">>>" + taskNum + "任务启动 "); Date dateTmp1 = new Date(); System.out.println(" "+taskNum+"任务干活中..."); 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) throws ExecutionException, InterruptedException { System.out.println("----程序开始运行----"); Date date1 = new Date(); String arr[]={"张一","钱二","孙三","李四","周五"}; int taskSize = 5; // 创建一个线程池 ExecutorService pool = Executors.newFixedThreadPool(taskSize); // 创建多个有返回值的任务 List<Future> list = new ArrayList<Future>(); for (int i = 0; i < taskSize; i++) { Callable c = new MyCallable(i + " ");// arr[i] 参数可有可无 // 执行任务并获取Future对象 Future f = pool.submit(c); // System.out.println(">>>" + f.get().toString()); //一个任务一个任务的依次执行完毕,不再需要ArrayList了 list.add(f); } // 关闭线程池 pool.shutdown(); // 获取所有并发任务的运行结果 for (Future f : list) { // 从Future对象上获取任务的返回值,并输出到控制台,每一个线程都有返回结果 System.out.println(">>>" + f.get().toString()); } Date date2 = new Date(); System.out.println("----程序结束运行----,程序总的运行时间为 :" + (date2.getTime() - date1.getTime()) + "毫秒"); } } 代码说明: 上述代码中Executors类,提供了一系列工厂方法用于创先线程池,返回的线程池都实现了ExecutorService接口。 public static ExecutorService newFixedThreadPool(int nThreads) 创建固定数目线程的线程池。 public static ExecutorService newCachedThreadPool() --不限定数量 创建一个可缓存的线程池,调用execute 将重用以前构造的线程(如果线程可用)。如果现有线程没有可用的,则创建一个新线程并添加到池中。终止并从缓存中移除那些已有 60 秒钟未被使用的线程。 public static ExecutorService newSingleThreadExecutor() --单线程 创建一个单线程化的Executor。 一次只跑一个线程。 public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) 创建一个支持定时及周期性的任务执行的线程池,多数情况下可用来替代Timer类。 newWorkStealingPool 系统时间有空闲时偷偷执行

    ExecutoreService提供了submit()方法,传递一个Callable,或Runnable,返回Future。如果Executor后台线程池还没有完成Callable的计算,这调用返回Future对象的get()方法获取返回值,会阻塞直到计算完成。
    转载请注明原文地址: https://ju.6miu.com/read-661369.html

    最新回复(0)