欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

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

程序员文章站 2024-02-29 20:51:34
本文实例讲述了java实现在不同线程中运行的代码。分享给大家供大家参考,具体如下: start()方法开始为一个线程分配cpu时间,这导致对run()方法的调用。...

本文实例讲述了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();
 }
}

运行结果如下:

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

希望本文所述对大家java程序设计有所帮助。