首页 > 解决方案 > 如何在我的查找器类中使用睡眠方法

问题描述

我正在开发一个多线程程序。有人可以帮助我如何在我的程序中实现睡眠方法。我从来没有使用过它,要求是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();
    }


}

标签: javamultithreadingoop

解决方案


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");
    }
}


推荐阅读