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

java語(yǔ)言

java多線程介紹

時(shí)間:2025-05-28 15:22:17 java語(yǔ)言 我要投稿

java多線程介紹

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

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

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

  Thread類

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

  2、Start()開(kāi)始執(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();

  }

  }

  多個(gè)線程共享一個(gè)實(shí)例的時(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é)果如下所示:

  Thread-1

  Thread-0

  1

  Thread-1

  1

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

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

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

  Thread(Runnable target)

  分配新的 Thread 對(duì)象。

  Thread(Runnable target,String name)

  分配新的 Thread 對(duì)象。

  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-15

關(guān)于Java多線程介紹09-09

java的多線程09-09

java多線程08-31

Java多線程知識(shí)點(diǎn)介紹09-05

java語(yǔ)言的多線程08-29

java多線程教程11-03

如何使用java多線程08-23

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