av手机免费在线观看,国产女人在线视频,国产xxxx免费,捆绑调教一二三区,97影院最新理论片,色之久久综合,国产精品日韩欧美一区二区三区

java語言

java多線程

時間:2025-05-11 05:47:06 java語言 我要投稿

java多線程

  JAVA多線程實(shí)現(xiàn)方式主要有三種:繼承Thread類、實(shí)現(xiàn)Runnable接口、使用ExecutorService、Callable、Future實(shí)現(xiàn)有返回結(jié)果的多線程,以下是小編為大家搜索整理的java多線程,歡迎閱讀!更多精彩內(nèi)容請及時關(guān)注我們應(yīng)屆畢業(yè)生考試網(wǎng)!

  多線程的基本實(shí)現(xiàn)

  進(jìn)程指運(yùn)行中的程序,每個進(jìn)程都會分配一個內(nèi)存空間,一個進(jìn)程中存在多個線程,啟動一個JAVA虛擬機(jī),就是打開個一個進(jìn)程,一個進(jìn)程有多個線程,當(dāng)多個線程同時進(jìn)行,就叫并發(fā)。

  Java創(chuàng)建線程的兩種方式為: 繼承Thread類 和實(shí)現(xiàn)Runnable接口

  Thread類

  1、通過覆蓋run方法實(shí)現(xiàn)線程要執(zhí)行的程序代碼

  2、Start()開始執(zhí)行多線程

  package com.bin.duoxiancheng;

  public class d1 extends Thread{

  public void run(){

  for(int i=0 ; i<50; i++){

  System.out.println(i);

  System.out.println(currentThread()。getName());

  try {

  sleep(100);

  } catch (InterruptedException e) {

  // TODO Auto-generatedcatch block

  e.printStackTrace();

  }

  }

  }

  public static void main(String[] args){

  new d1()。start();

  new d1()。start();

  }

  }

  多個線程共享一個實(shí)例的時候,代碼代碼如下:

  package com.bin.duoxiancheng;

  public class d1 extends Thread{

  int i=0;

  public void run(){

  for(i=0 ; i<50; i++){

  System.out.println(i);

  System.out.println(currentThread()。getName());

  try {

  sleep(100);

  } catch (InterruptedException e) {

  // TODO Auto-generatedcatch block

  e.printStackTrace();

  }

  }

  }

  public static void main(String[] args){

  new d1()。start();

  new d1()。start();

  }

  }

  結(jié)果如下所示:

  0

  Thread-1

  0

  Thread-0

  1

  Thread-1

  1

  實(shí)際2個線程在操縱不同的變量a,在執(zhí)行run方法時候,線程把a(bǔ)都當(dāng)做自己的變量在執(zhí)行。

  Runnable接口實(shí)現(xiàn)多線程

  當(dāng)一個繼承自Thread時,就不能再繼承其他類,使用Runnable接口解決了此問題,在新建一個Thread類中,在構(gòu)造方法中初始化

  Thread(Runnable target)

  分配新的 Thread 對象。

  Thread(Runnable target,String name)

  分配新的 Thread 對象。

  package com.bin.duoxiancheng;

  public class D2 implements Runnable{

  int i=0;

  public void run(){

  for(i=0 ; i<50; i++){

  System.out.println(i);

  System.out.println(Thread.currentThread()。getName());

  try {

  Thread.sleep(100);

  } catch (InterruptedException e) {

  // TODO Auto-generatedcatch block

  e.printStackTrace();

  }

  }

  }

  public static void main(String[] args){

  D2 d=new D2();

  Thread t=new Thread(d);

  t.start();

  }

  }

【java多線程】相關(guān)文章:

java的多線程09-09

java語言的多線程08-29

java多線程介紹08-23

java多線程教程11-03

如何使用java多線程08-23

Java多線程問題總結(jié)10-24

Java使用多線程的優(yōu)勢07-10

Java多線程基本使用11-08

Java多線程的用法介紹09-15