java - 如何在我的查找器类中使用睡眠方法
问题描述
我正在开发一个多线程程序。有人可以帮助我如何在我的程序中实现睡眠方法。我从来没有使用过它,要求是run方法使用sleep方法。我确实启动了 4 个线程并检查了概述的范围。我应该修改 Finder 类,使其运行方法利用睡眠方法。我从来没有使用过睡眠方法。
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() 将暂停正在执行该调用的当前线程。
所以我的猜测是你应该Thread.sleep
在 Finder 的运行函数中调用。
编辑 实施将只是调用我解释的内容:
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");
}
}
推荐阅读
- spyder - Spyder 代码分析“无效的转义序列”,带有正则表达式结构,如 `\d`
- objective-c - 获取无法创建“JumioNetverifyBinding.NetverifyConfiguration”类型的本机实例,本机类尚未加载异常
- sql - 有没有办法使用可用的提供程序从共享点列表中检索数据?
- javascript - CSS 分页媒体总页数减去封面页数
- mysql - JPA 列定义不适用于 H2 数据库的 COMMENT
- python - 如何识别 Project_Code、File_Name、File_Format。并基于此创建新的文件夹结构
- reactjs - 将页面转换添加到 Nextjs 的最佳方法是什么?
- ubuntu - Ubuntu 20.04.2.0 LTS 自动禁用二进制的 RWX 段
- javascript - 反应原生,在时间 ==60 时调用 setInterval 内的函数
- wpf - 如何在 C# WPF 中将空文本的提示信息添加到文本框?