JAVA程序设计,多线程,求大神给一份可运行的代码

JAVA程序设计,多线程,求大神给一份可运行的代码Java程序设计,多线程1、创建线程类,线程的run方法中实现n次空循环,线程运行时显示线程名和是第几次循环,然后休息一... JAVA程序设计,多线程,求大神给一份可运行的代码Java程序设计,多线程
1、创建线程类,线程的run方法中实现n次空循环,线程运行时显示线程名和是第几次循环,然后休息一段时间。创建3个线程进行测试。
展开
 我来答
samismiling
2017-06-07 · 知道合伙人软件行家
samismiling
知道合伙人软件行家
采纳数:1340 获赞数:5604

向TA提问 私信TA
展开全部

给你一个经典的例子。run里面放空循环来观察多线程是不合理的,空循环消耗时序极小,用sleep来间隔时间才是合理的。

class RunnableDemo implements Runnable {
   private Thread t;
   private String threadName;
   
   RunnableDemo( String name) {
      threadName = name;
      System.out.println("Creating " +  threadName );
   }
   
   public void run() {
      System.out.println("Running " +  threadName );
      try {
         for(int i = 4; i > 0; i--) {
            System.out.println("Thread: " + threadName + ", " + i);
            // Let the thread sleep for a while.
            Thread.sleep(50);
         }
      }catch (InterruptedException e) {
         System.out.println("Thread " +  threadName + " interrupted.");
      }
      System.out.println("Thread " +  threadName + " exiting.");
   }
   
   public void start () {
      System.out.println("Starting " +  threadName );
      if (t == null) {
         t = new Thread (this, threadName);
         t.start ();
      }
   }
}

public class TestThread {

   public static void main(String args[]) {
      RunnableDemo R1 = new RunnableDemo( "Thread-1");
      R1.start();
      
      RunnableDemo R2 = new RunnableDemo( "Thread-2");
      R2.start();
   }   
}
追问
谢谢
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式