java语言

Java实现在不同线程中运行的代码实例详解

时间:2024-06-11 03:48:10 java语言 我要投稿
  • 相关推荐

Java实现在不同线程中运行的代码实例详解

  本文实例讲述了Java实现在不同线程中运行的代码。下面是由百分网小编为大家整理的Java实现在不同线程中运行的代码实例详解,喜欢的可以收藏一下!了解更多详情资讯,请关注应届毕业生考试网!

  start()方法开始为一个线程分配CPU时间,这导致对run()方法的调用。

  代码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运行结果如下:

【Java实现在不同线程中运行的代码实例详解】相关文章:

java中通用的线程池实例代码08-27

java多线程-线程通信实例详细解读04-02

java多线程同步块实例讲解素材04-02

Java线程编程中的主线程详细介绍04-02

java的多线程12-04

java多线程03-27

Java中的多态用法实例分析04-04

举例讲解Java中的多线程范文欣赏04-03

java语言的多线程11-25