欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java創(chuàng)建多線程的幾種方式實(shí)現(xiàn)

 更新時(shí)間:2020年10月27日 10:44:38   作者:liangtengyu  
這篇文章主要介紹了Java創(chuàng)建多線程的幾種方式實(shí)現(xiàn),文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧

1、繼承Thread類,重寫run()方法

//方式1
package cn.itcats.thread.Test1;

public class Demo1 extends Thread{
 
 //重寫的是父類Thread的run()
 public void run() {
  System.out.println(getName()+"is running...");
 }
 
 
 public static void main(String[] args) {
  Demo1 demo1 = new Demo1();
  Demo1 demo2 = new Demo1();
  demo1.start();
  demo2.start();
 }
}

2、實(shí)現(xiàn)Runnable接口,重寫run()

實(shí)現(xiàn)Runnable接口只是完成了線程任務(wù)的編寫
若要啟動(dòng)線程,需要new Thread(Runnable target),再有thread對(duì)象調(diào)用start()方法啟動(dòng)線程
此處我們只是重寫了Runnable接口的Run()方法,并未重寫Thread類的run(),讓我們看看Thread類run()的實(shí)現(xiàn)
本質(zhì)上也是調(diào)用了我們傳進(jìn)去的Runnale target對(duì)象的run()方法

//Thread類源碼中的run()方法
//target為Thread 成員變量中的 private Runnable target;

 @Override
 public void run() {
  if (target != null) {
   target.run();
  }
 }

所以第二種創(chuàng)建線程的實(shí)現(xiàn)代碼如下:

package cn.itcats.thread.Test1;

/**
 * 第二種創(chuàng)建啟動(dòng)線程的方式
 * 實(shí)現(xiàn)Runnale接口
 * @author fatah
 */
public class Demo2 implements Runnable{

  //重寫的是Runnable接口的run()
  public void run() {
      System.out.println("implements Runnable is running");
  }
  
  public static void main(String[] args) {
    Thread thread1 = new Thread(new Demo2());
    Thread thread2 = new Thread(new Demo2());
    thread1.start();
    thread2.start();
  }

 
}

實(shí)現(xiàn)Runnable接口相比第一種繼承Thread類的方式,使用了面向接口,將任務(wù)與線程進(jìn)行分離,有利于解耦

3、匿名內(nèi)部類的方式

適用于創(chuàng)建啟動(dòng)線程次數(shù)較少的環(huán)境,書寫更加簡(jiǎn)便
具體代碼實(shí)現(xiàn):

package cn.itcats.thread.Test1;
/**
 * 創(chuàng)建啟動(dòng)線程的第三種方式————匿名內(nèi)部類
 * @author fatah
 */
public class Demo3 {
  public static void main(String[] args) {
    //方式1:相當(dāng)于繼承了Thread類,作為子類重寫run()實(shí)現(xiàn)
    new Thread() {
      public void run() {
        System.out.println("匿名內(nèi)部類創(chuàng)建線程方式1...");
      };
    }.start();
    
    
    
    //方式2:實(shí)現(xiàn)Runnable,Runnable作為匿名內(nèi)部類
    new Thread(new Runnable() {
      public void run() {
        System.out.println("匿名內(nèi)部類創(chuàng)建線程方式2...");
      }
    } ).start();
  }
}

4、帶返回值的線程(實(shí)現(xiàn)implements Callable<返回值類型>)

以上兩種方式,都沒有返回值且都無(wú)法拋出異常。
Callable和Runnbale一樣代表著任務(wù),只是Callable接口中不是run(),而是call()方法,但兩者相似,即都表示執(zhí)行任務(wù),call()方法的返回值類型即為Callable接口的泛型
具體代碼實(shí)現(xiàn):

package cn.itcats.thread.Test1;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
import java.util.concurrent.RunnableFuture;

/**
 * 方式4:實(shí)現(xiàn)Callable<T> 接口
 * 含返回值且可拋出異常的線程創(chuàng)建啟動(dòng)方式
 * @author fatah
 */
public class Demo5 implements Callable<String>{

  public String call() throws Exception {
    System.out.println("正在執(zhí)行新建線程任務(wù)");
    Thread.sleep(2000);
    return "新建線程睡了2s后返回執(zhí)行結(jié)果";
  }

  public static void main(String[] args) throws InterruptedException, ExecutionException {
    Demo5 d = new Demo5();
    /*  call()只是線程任務(wù),對(duì)線程任務(wù)進(jìn)行封裝
      class FutureTask<V> implements RunnableFuture<V>
      interface RunnableFuture<V> extends Runnable, Future<V>
    */
    FutureTask<String> task = new FutureTask<>(d);
    Thread t = new Thread(task);
    t.start();
    System.out.println("提前完成任務(wù)...");
    //獲取任務(wù)執(zhí)行后返回的結(jié)果
    String result = task.get();
    System.out.println("線程執(zhí)行結(jié)果為"+result);
  }
  
}

5、定時(shí)器(java.util.Timer)

關(guān)于Timmer的幾個(gè)構(gòu)造方法


執(zhí)行定時(shí)器任務(wù)使用的是schedule方法:


具體代碼實(shí)現(xiàn):

package cn.itcats.thread.Test1;

import java.util.Timer;
import java.util.TimerTask;

/**
 * 方法5:創(chuàng)建啟動(dòng)線程之Timer定時(shí)任務(wù)
 * @author fatah
 */
public class Demo6 {
  public static void main(String[] args) {
    Timer timer = new Timer();
    timer.schedule(new TimerTask() {
      @Override
      public void run() {
        System.out.println("定時(shí)任務(wù)延遲0(即立刻執(zhí)行),每隔1000ms執(zhí)行一次");
      }
    }, 0, 1000);
  }
  
}

我們發(fā)現(xiàn)Timer有不可控的缺點(diǎn),當(dāng)任務(wù)未執(zhí)行完畢或我們每次想執(zhí)行不同任務(wù)時(shí)候,實(shí)現(xiàn)起來(lái)比較麻煩。這里推薦一個(gè)比較優(yōu)秀的開源作業(yè)調(diào)度框架“quartz”,在后期我可能會(huì)寫一篇關(guān)于quartz的博文。

6、線程池的實(shí)現(xiàn)(java.util.concurrent.Executor接口)

降低了創(chuàng)建線程和銷毀線程時(shí)間開銷和資源浪費(fèi)
具體代碼實(shí)現(xiàn):

package cn.itcats.thread.Test1;

import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

public class Demo7 {
  public static void main(String[] args) {
    //創(chuàng)建帶有5個(gè)線程的線程池
    //返回的實(shí)際上是ExecutorService,而ExecutorService是Executor的子接口
    Executor threadPool = Executors.newFixedThreadPool(5);
    for(int i = 0 ;i < 10 ; i++) {
      threadPool.execute(new Runnable() {
        public void run() {
          System.out.println(Thread.currentThread().getName()+" is running");
        }
      });
    }
    
  }
}

運(yùn)行結(jié)果:

pool-1-thread-3 is running
pool-1-thread-1 is running
pool-1-thread-4 is running
pool-1-thread-3 is running
pool-1-thread-5 is running
pool-1-thread-2 is running
pool-1-thread-5 is running
pool-1-thread-3 is running
pool-1-thread-1 is running
pool-1-thread-4 is running

運(yùn)行完畢,但程序并未停止,原因是線程池并未銷毀,若想銷毀調(diào)用threadPool.shutdown(); 注意需要把我上面的
Executor threadPool = Executors.newFixedThreadPool(10); 改為
ExecutorService threadPool = Executors.newFixedThreadPool(10); 否則無(wú)shutdown()方法

若創(chuàng)建的是CachedThreadPool則不需要指定線程數(shù)量,線程數(shù)量多少取決于線程任務(wù),不夠用則創(chuàng)建線程,夠用則回收。

7、Lambda表達(dá)式的實(shí)現(xiàn)(parallelStream)

package cn.itcats.thread.Test1;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 使用Lambda表達(dá)式并行計(jì)算
 * parallelStream
 * @author fatah
 */
public class Demo8 {
  public static void main(String[] args) {
    List<Integer> list = Arrays.asList(1,2,3,4,5,6);
    Demo8 demo = new Demo8();
    int result = demo.add(list);
    System.out.println("計(jì)算后的結(jié)果為"+result);
  }
  
  public int add(List<Integer> list) {
    //若Lambda是串行執(zhí)行,則應(yīng)順序打印
    list.parallelStream().forEach(System.out :: println);
    //Lambda有stream和parallelSteam(并行)
    return list.parallelStream().mapToInt(i -> i).sum();
  }
}

運(yùn)行結(jié)果:

4
1
3
5
6
2

計(jì)算后的結(jié)果為21

事實(shí)證明是并行執(zhí)行

8、Spring實(shí)現(xiàn)多線程

(1)新建Maven工程導(dǎo)入spring相關(guān)依賴
(2)新建一個(gè)java配置類(注意需要開啟@EnableAsync注解——支持異步任務(wù))

package cn.itcats.thread;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;

@Configuration
@ComponentScan("cn.itcats.thread")
@EnableAsync
public class Config {
  
}

(3)書寫異步執(zhí)行的方法類(注意方法上需要有@Async——異步方法調(diào)用)

package cn.itcats.thread;

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncService {
  
  @Async
  public void Async_A() {
    System.out.println("Async_A is running");
  }
  
  @Async
  public void Async_B() {
    System.out.println("Async_B is running");
  }
}

(4)創(chuàng)建運(yùn)行類

package cn.itcats.thread;

import org.springframework.context.annotation.AnnotationConfigApplicationContext;

public class Run {
  public static void main(String[] args) {
    //構(gòu)造方法傳遞Java配置類Config.class
    AnnotationConfigApplicationContext ac = new AnnotationConfigApplicationContext(Config.class);
    AsyncService bean = ac.getBean(AsyncService.class);
    bean.Async_A();
    bean.Async_B();
  }
}

到此這篇關(guān)于Java創(chuàng)建多線程的幾種方式實(shí)現(xiàn)的文章就介紹到這了,更多相關(guān)Java創(chuàng)建多線程內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

  • SpringBoot整合MybatisPlus的教程詳解

    SpringBoot整合MybatisPlus的教程詳解

    這篇文章主要介紹了SpringBoot整合MybatisPlus的方法,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-11-11
  • springboot整合Nginx實(shí)現(xiàn)負(fù)載均衡反向代理的方法詳解

    springboot整合Nginx實(shí)現(xiàn)負(fù)載均衡反向代理的方法詳解

    這篇文章主要給大家介紹了關(guān)于springboot整合Nginx實(shí)現(xiàn)負(fù)載均衡反向代理的相關(guān)資料,文中通過(guò)圖文以及實(shí)例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下
    2022-01-01
  • idea生成類注釋和方法注釋的正確方法(推薦)

    idea生成類注釋和方法注釋的正確方法(推薦)

    這篇文章主要介紹了idea生成類注釋和方法注釋的正確方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-11-11
  • com.mysql.jdbc.Driver 和 com.mysql.cj.jdbc.Driver的區(qū)別及設(shè)定serverTimezone的方法

    com.mysql.jdbc.Driver 和 com.mysql.cj.jdbc.Driver的區(qū)

    這篇文章主要介紹了com.mysql.jdbc.Driver 和 com.mysql.cj.jdbc.Driver的區(qū)別以及設(shè)定serverTimezone的方法,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2023-09-09
  • Java反射機(jī)制如何解決數(shù)據(jù)傳值為空的問(wèn)題

    Java反射機(jī)制如何解決數(shù)據(jù)傳值為空的問(wèn)題

    這篇文章主要介紹了Java反射機(jī)制如何解決數(shù)據(jù)傳值為空的問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2022-03-03
  • Mybatis主配置文件的properties標(biāo)簽詳解

    Mybatis主配置文件的properties標(biāo)簽詳解

    這篇文章主要介紹了Mybatis主配置文件的properties標(biāo)簽,本文給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下
    2020-08-08
  • FastJson對(duì)于JSON格式字符串、JSON對(duì)象及JavaBean之間的相互轉(zhuǎn)換操作

    FastJson對(duì)于JSON格式字符串、JSON對(duì)象及JavaBean之間的相互轉(zhuǎn)換操作

    這篇文章主要介紹了FastJson對(duì)于JSON格式字符串、JSON對(duì)象及JavaBean之間的相互轉(zhuǎn)換,非常不錯(cuò),具有參考借鑒價(jià)值,需要的朋友可以參考下
    2017-11-11
  • 教你如何使用Java實(shí)現(xiàn)WebSocket

    教你如何使用Java實(shí)現(xiàn)WebSocket

    這篇文章主要介紹了教你如何使用Java實(shí)現(xiàn)WebSocket問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-06-06
  • Keycloak各種配置及API的使用說(shuō)明

    Keycloak各種配置及API的使用說(shuō)明

    這篇文章主要介紹了Keycloak各種配置及API的使用說(shuō)明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教
    2023-03-03
  • SpringBoot中Filter沒有生效原因及解決方案

    SpringBoot中Filter沒有生效原因及解決方案

    Servlet 三大組件 Servlet、Filter、Listener 在傳統(tǒng)項(xiàng)目中需要在 web.xml 中進(jìn)行相應(yīng)的配置,這篇文章主要介紹了SpringBoot中Filter沒有生效原因及解決方案,需要的朋友可以參考下
    2024-04-04

最新評(píng)論