在Android中實現多線程同步

來源:互聯網
上載者:User
 1. java中對多線程存取控制可使用關鍵字synchronized
下面將以Producer Consumer模型介紹android中線程同步的使用。

步驟:
建立一android project,
修改main activity如下:

代碼:

package com.test.thread;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

public class MultiThread extends Activity {
   
    private static final String MultiThread_ACTIVITY_TAG = "MultiThread_TAG";
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
       
        CubbyHole c = new CubbyHole();
        Producer p1 = new Producer(c, 1);
        Consumer c1 = new Consumer(c, 1);
       
        p1.start();
        c1.start();
       
        // Test log system.
        //testLog();
       
        setContentView(R.layout.main);
       
    }
   
    // This is a example to use android.util.Log.
    public void testLog() { 
        Log.i(MultiThread_ACTIVITY_TAG, "============================="); 
       
        Log.d(MultiThread_ACTIVITY_TAG, "this is a DEBUG of MyAndroid. "); 
        Log.i(MultiThread_ACTIVITY_TAG, "this is a INFO of MyAndroid. "); 
        Log.w(MultiThread_ACTIVITY_TAG, "this is a WARNING of MyAndroid. ");  
    } 
   
   
    public class Producer extends Thread {
        private CubbyHole cubbyhole;
        private int number;

        public Producer(CubbyHole c, int number) {
            cubbyhole = c;
            this.number = number;
        }

        public void run() {
            for (int i = 0; i < 10; i++) {
                cubbyhole.put(i);
                Log.d(MultiThread_ACTIVITY_TAG, "Producer #" + this.number + " put: " + i);
                //System.out.println("Producer #" + this.number + " put: " + i);
                try {
                    sleep((int)(Math.random() * 100));
                } catch (InterruptedException e) {}
            }
        }
    }

    public class CubbyHole {
        private int contents;
        private boolean available = false;
   
        public synchronized int get() {
            while (available == false) {
                try {
                    wait();
                    } catch (InterruptedException e) { }
            }
           
            available = false;
            notifyAll();
            return contents;
        }
   
        public synchronized void put(int value) {
            while (available == true) {
                try {
                    wait();
                    } catch (InterruptedException e) { }
            }
            contents = value;
            available = true;
            notifyAll();
        }
    }
   
   
    public class Consumer extends Thread {
        private CubbyHole cubbyhole;
        private int number;
   
        public Consumer(CubbyHole c, int number) {
            cubbyhole = c;
            this.number = number;
        }
   
        public void run() {
            int value = 0;
            for (int i = 0; i < 10; i++) {
                value = cubbyhole.get();
                Log.d(MultiThread_ACTIVITY_TAG, "Consumer #" + this.number + " got: " + value);
                //System.out.println("Consumer #" + this.number + " got: " + value);
            }
        }
    }
}

2. 上面的代碼中引入了android.util.Log包, 以擁有debug。
    運行上面的工程後,在dbg視窗的Logcat區,顯示打出的log。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.