源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

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

  • 时间:2022-07-12 06:57 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Java实现在不同线程中运行的代码实例
本文实例讲述了Java实现在不同线程中运行的代码。分享给大家供大家参考,具体如下: [img]http://files.jb51.net/file_images/article/201704/2017412120240090.jpg?201731212331[/img] 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();
 }
}

[url=http://www.1sucai.cn/softs/390522.html][b]eclipse[/b][/url]运行结果如下: [img]http://files.jb51.net/file_images/article/201704/2017412141012164.jpg?2017312141035[/img] 希望本文所述对大家java程序设计有所帮助。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部