我正在开发一个多线程程序。有人可以帮助我如何在我的程序中实现sleep方法。我从未使用过它,要求是run方法使用sleep方法。我确实启动了4个线程并检查了概述的范围。我应该修改Finder类,使其运行方法利用sleep方法。我从未使用过睡眠方法。
import static java.lang.System.out;
class Range
{
int start;
int end;
Range(int s, int e)
{
start = s;
end = e;
}
boolean contains(int x)
{
return end - start >=0;
}
}
class Finder implements Runnable
{
@Override
public void run()
{
}
}
public class ThreadTest implements Runnable
{
static void log(Object o){out.print(o);}
static void logLn(Object o){out.println(o);}
/**
* When an object implementing interface <code>Runnable</code> is used
* to create a thread, starting the thread causes the object's
* <code>run</code> method to be called in that separately executing
* thread.
* <p>
* The general contract of the method <code>run</code> is that it may
* take any action whatsoever.
*
* @see Thread#run()
*/
@Override
public void run()
{
logLn("Running main");
}
static Range myRange = new Range(100, 500);
public static void main(String[] args)
{
if (myRange.contains(300))
{
System.out.println ("You\'re within the correct range.");
}
Finder fc = new Finder();
Thread t1= new Thread(fc);
t1.start();
Thread t2= new Thread(fc);
t2.start();
Thread t3 = new Thread(fc);
t3.start();
Thread t4 = new Thread(fc);
t4.start();
Runnable myRunnable = new Runnable(){
public void run(){
System.out.println("Runnable running");
}
};
myRunnable.run();
}
}
最佳答案
Sleep是Thread类通过Thread.sleep(1000L)
提供的静态方法,其中您传递的值是代表毫秒的Long值。实现sleep方法没有多大意义,但是调用Thread.sleep()将暂停正在执行该调用的当前线程。
所以我的猜测是您应该在Finder的run函数中调用Thread.sleep
。
编辑
实现只是调用我解释的内容:
class Finder implements Runnable{
@Override
public void run(){
System.out.println("Thread " + Thread.currentThread().getId() + " sleeping");
Thread.sleep(1500L);
System.out.println("Thread " + Thread.currentThread().getId() + " awake");
}
}