
JAVA程序设计,多线程,求大神给一份可运行的代码
JAVA程序设计,多线程,求大神给一份可运行的代码Java程序设计,多线程1、创建线程类,线程的run方法中实现n次空循环,线程运行时显示线程名和是第几次循环,然后休息一...
JAVA程序设计,多线程,求大神给一份可运行的代码Java程序设计,多线程
1、创建线程类,线程的run方法中实现n次空循环,线程运行时显示线程名和是第几次循环,然后休息一段时间。创建3个线程进行测试。 展开
1、创建线程类,线程的run方法中实现n次空循环,线程运行时显示线程名和是第几次循环,然后休息一段时间。创建3个线程进行测试。 展开
1个回答
展开全部
给你一个经典的例子。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();
}
}
追问
谢谢
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询