技術(shù)員聯(lián)盟提供win764位系統(tǒng)下載,win10,win7,xp,裝機(jī)純凈版,64位旗艦版,綠色軟件,免費(fèi)軟件下載基地!

當(dāng)前位置:主頁(yè) > 教程 > 服務(wù)器類(lèi) >

Java實(shí)現(xiàn)在不同線(xiàn)程中運(yùn)行的代碼實(shí)例詳解

來(lái)源:技術(shù)員聯(lián)盟┆發(fā)布時(shí)間:2017-11-07 12:33┆點(diǎn)擊:

  本文實(shí)例講述了Java實(shí)現(xiàn)在不同線(xiàn)程中運(yùn)行的代碼。分享給大家供大家參考,具體如下:

Java實(shí)現(xiàn)在不同線(xiàn)程中運(yùn)行的代碼實(shí)例詳解 三聯(lián)

  start()方法開(kāi)始為一個(gè)線(xiàn)程分配CPU時(shí)間,這導(dǎo)致對(duì)run()方法的調(diào)用。

  代碼1

  package Threads;

  /**

  * Created by Frank

  */

  public class ThreadsDemo1 extends Thread {

  private String msg;

  private int count;

  public ThreadsDemo1(final String msg, int n) {

  this.msg = msg;

  count = n;

  setName(msg + " runner Thread");

  }

  public void run() {

  while (count-- > 0) {

  System.out.println(msg);

  try {

  Thread.sleep(100);

  } catch (InterruptedException e) {

  return;

  }

  }

  System.out.println(msg + " all done.");

  }

  public static void main(String[] args) {

  new ThreadsDemo1("Hello from X", 10).start();

  new ThreadsDemo1("Hello from Y", 15).start();

  }

  }

  代碼2:

  package Threads;

  /**

  * Created by Frank

  */

  public class ThreadsDemo2 implements Runnable {

  private String msg;

  private Thread t;

  private int count;

  public static void main(String[] args) {

  new ThreadsDemo2("Hello from X", 10);

  new ThreadsDemo2("Hello from Y", 15);

  }

  public ThreadsDemo2(String m, int n) {

  this.msg = m;

  count = n;

  t = new Thread(this);

  t.setName(msg + "runner Thread");

  t.start();

  }

  public void run() {

  while (count-- > 0) {

  System.out.println(msg);

  try {

  Thread.sleep(100);

  } catch (InterruptedException e) {

  return;

  }

  }

  System.out.println(msg + " all done.");

  }

  }

  代碼3:

  package Threads;

  /**

  * Created by Frank

  */

  public class ThreadsDemo3 {

  private int count;

  public static void main(String[] args) {

  new ThreadsDemo3("Hello from X", 10);

  new ThreadsDemo3("Hello from Y", 15);

  }

  public ThreadsDemo3(final String msg, int n) {

  this.count = n;

  Thread t = new Thread(new Runnable() {

  public void run() {

  while (count-- > 0) {

  System.out.println(msg);

  try {

  Thread.sleep(100);

  } catch (InterruptedException e) {

  return;

  }

  }

  System.out.println(msg + " all done.");

  }

  });

  t.setName(msg + " runner Thread");

  t.start();

  }

  }

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

Java實(shí)現(xiàn)在不同線(xiàn)程中運(yùn)行的代碼實(shí)例詳解