一个线程等待另一个方法

时间:2015-03-26 22:02:53

标签: java multithreading concurrency synchronization

我有一个线程(A)开始另一个(B)。线程A必须等待线程B的初始化方法在继续之前完成。

我目前正在使用线程B作为锁定:

synchronized (B) {

            try {

                B.start();

                while (!B.getIsInitialized()) {
                    B.wait();
                }
            } catch (InterruptedException e) {
                Log.logStackTrace(this + " run: Exception detected", e);
            }
        }

在B& run方法的最开始,我有以下内容:

synchronized(this) {

        initialize();

        notify();
    }

这一切似乎都有效,但我无法在网上找到关于使用两个线程中的一个作为锁的信息。我做的正确吗?我还应该注意,一旦初始化完成,线程B不会终止,并且需要继续,所以我不能简单地使用.join()。

感谢您的时间。

1 个答案:

答案 0 :(得分:0)

这个代码肯定会用于您想要实现的目标。我要提到的唯一想法是尝试尽可能少地使用synchronized,因为同步是“昂贵的”。因此,如果代码的某些部分不需要处于同步部分,则不要。这部分代码将执行相同的操作,但仅在线程B中进行同步。

public class Test {
 public static void main(String[] args) {       
     new ThreadA().start();
  }
}


class ThreadA extends Thread{       
    private void startThreadB(){
        ThreadB tb=new ThreadB();
        tb.start();                 
        // to some code if you need;
        tb.isInit();
    }

    public void run(){
            System.out.println("Thread A is started ");
            startThreadB(); 
            while(true){
                // your code for execution of thread A
                System.out.println("thread A is working");
                try{ Thread.sleep(2000);} catch(Exception e){}
            }
    }       
}



  class ThreadB extends Thread{
     private boolean init;               
     public ThreadB(){   init=false;     }
     private void init(){
         // some code here for init
         synchronized(this){
               init= true;
               notifyAll();
               System.out.println("Thread B has been inicialized !");
         }
     }


     public void isInit(){
         synchronized(this){
             while(!init) { try{ wait();}catch(InterruptedException e){}}
         }
     }

    public void run(){
        System.out.println("Thread B is started");
        init();
        while(true){
            // your code for execution of thread B
            System.out.println("Thread B is working");
            try{ Thread.sleep(2000);} catch(Exception e){}
        }
    }
}