【问题标题】:Threads execute not at the same time线程不同时执行
【发布时间】:2014-05-18 14:04:58
【问题描述】:

我有三个线程,每个线程必须定期对同一类 (Q) 的实例 (q) 进行一些操作(这就是我在 somecheck 方法中使用 Thread.sleep() 的原因)。主要任务是使线程不同时执行,因此一次只能执行一个线程。 我尝试将每个线程的 run 方法的内容放入 synchronized (q){},但我不明白在哪里放置 notify 和 wait 方法。

class Q {
        boolean somecheck(int threadSleepTime){
        //somecheck__section, if I want to stop thread - return false;

            try{
            Thread.sleep(threadSleepTime);
            } catch (InterruptedException e) {                
            }
            return true;
        }
}



class threadFirst extends Thread  {
    private Q q;
    threadFirst(Q q){this.q=q;}

    public void run(){
        do{
            //Working with object of class Q
        }
        while(q.somecheck(10));
    }
}

class threadSecond extends Thread  {
    private Q q;
    threadSecond(Q q){this.q=q;}

    public void run(){
        do{
            //Working with object of class Q
        }
        while(q.somecheck(15));
    }
}

class threadThird extends Thread  {

    private Q q;
    threadThird(Q q){this.q=q;}

    public void run(){
        do{
            //Working with object of class Q
        }
        while(q.somecheck(20));
    }
}

class run{
    public static void main(String[] args) {
        Q q = new Q();
        threadFirst t1 = new threadFirst(q);
        threadSecond t2 = new threadSecond(q);
        threadThird t3 = new threadThird(q);
        t1.start();
        t2.start();
        t3.start();
    }
}

【问题讨论】:

  • 是的!一切正常,但线程不同步,线程同时执行。
  • 你的代码有很多错误,我们很难处理。
  • 这段代码甚至无法编译,要么按照已经提出的要求修复它,要么将其删除
  • 你是对的!我已经修好了!

标签: java multithreading


【解决方案1】:

如果您在所有方法中使用synchronized 块,则不需要放置任何notify()wait() 方法,例如:

class threadFirst extends Thread {
    ...
    public void run() {
        synchronized (q) {
            //your loop here
        }
    }
    ...
}

【讨论】:

  • 您的想法意味着-第一个线程将执行并停止,然后第二个线程将执行并停止,第三个线程将执行并停止。但是,洞的想法是在第一个线程中做某事,然后另一个线程会做某事,而不是第一个线程可以再次做某事。
  • 线程执行“Working with class of Q”部分并执行q.somecheck()后,线程需要给其他线程执行的机会。
  • @user2963950 好像我已经知道了,那么你可以将synchronized 块移动到循环体中
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-11-26
  • 2019-02-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多