synchronized 塊

jackie_gnu發表於2011-09-15
方法一.
private class Worker implements Runnable {
    private Object mLock = new Object();
    private int spantime = 100;
    private boolean bResult = false;

    public Worker(int spantime) {
        Log.v(TAG, " TestThread constructor");
        this.spantime = spantime;

        new Thread(this).start();
    }

    @Override
    public void run() {
        Log.v(TAG, " TestThread run");

        synchronized (mLock) {
            try {
                Thread.sleep(spantime);
                bResult = true;
                Log.v(TAG, "current thread = " + Thread.currentThread().getName() +  " worker thread .... count = " + count++);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            mLock.notifyAll();
        }
    }

    boolean getResult() {
        synchronized (mLock) {
            try {
                mLock.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        return bResult;
    }
}


 方法二

 public void onClick(View v) {
         AThread thr = new AThread();
         thr.start();
         synchronized(thr){
                 try {
                         //Thread.sleep(1000);
                         thr.wait();
                         Log.v(TAG, " sleep 1000 --> 2");
                 } catch (InterruptedException e) {
                         // TODO Auto-generated catch block
                         e.printStackTrace();
                 }
         }

         synchronized(thr){
                 thr.mReady = true;
                 Log.v(TAG, " set mReady = true ---> 3");
                 thr.notifyAll();
         }
 }

 class AThread extends Thread{
         public boolean mReady = false;

         public AThread(){
                 super("Athread");
         }

         public void run(){
                 Looper.prepare();

                 synchronized (this){
                         try {
                                 Thread.sleep(1000);
                                 Log.v(TAG, " Thread notifyall -->1");
                                 this.notifyAll();
                         } catch (InterruptedException e) {
                                 // TODO Auto-generated catch block
                                 e.printStackTrace();
                         }
                 }

                 synchronized(this){
                         while (!mReady){
                                 try {
                                         wait();
                                         Log.v(TAG, " Thread wait ----> 4");
                                 } catch (InterruptedException e) {
                                         // TODO Auto-generated catch block
                                         e.printStackTrace();
                                 }
                         }
                 }

                 Looper.loop();
         }
 }


 

相關文章