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。