Java Thread sleep()帮助

时间:2014-12-02 22:22:54

标签: java multithreading

您好主要想法是,如果男性>女性,女性线程必须等待1000毫秒(1秒),然后再次检查。我试着寻找这个,但我无法找到解决方案。有人可以帮助我吗?(我刚刚开始学习线程)

public class A implements Runnable {

    public void run(){
    }

    public static void main(String[] args)throws InterruptedException {
        int n = 3;
        int m = 17;
        int f = 13;

        Thread th1 = new Thread(new male(m,n));

        Thread th2 = new Thread(new female(f,n));

        th1.start();
        th2.start();

        //not working
        if (m>f){
                th2.sleep(1000);
        }
        else if(f>m){
                th1.sleep(1000);    
        }
    }

}

class male extends A {

    public male(int male, int count){
        while(male>0){
            male -= count;
            System.out.println("m: " + male);
        }
    }
}

class female extends A {

    public female(int female, int count){
        while(female>0){
            female -= count;
            System.out.println("f: " + female);
        }
    }
}

2 个答案:

答案 0 :(得分:2)

Thread.sleep方法是一个static方法,它将当前线程"置于睡眠状态。一段时间。它不能用来让其他线程睡觉......就像你试图做的那样。

如果您希望子线程定期休眠,那么对sleep的调用需要由相应的线程本身进行;例如在各自的run()方法中。

对于它的价值......一个线程没有安全方式导致另一个线程进入休眠或暂停状态。有一个弃用的API用于暂停另一个线程,但它有许多安全和安全问题,不应该使用。


还有另一个问题。在实例化这些类时,将运行构建器中的逻辑。当你" new" MaleFemale个对象。您希望该代码在子线程中运行...当它们已经启动时。

您的MaleFemale类需要实现Runnable.run()方法,这就是需要实现线程逻辑的地方。

答案 1 :(得分:0)

对于初学者来说,不是让A类除了主方法之外没有任何东西,而是实现Runnable并且男性和女性扩展A,考虑让男性和女性自己实现Runnable。其次,你的男性和女性方法在run方法中什么都不包含,所以没有什么可以在另一个线程上运行。因此,你的主题一开始就什么都不做。