在Android中实现多线程同步
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。
本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/shilongdred1979/archive/2008/10/19/3080142.aspx
更多相关文章
- 箭头函数的基础使用
- NPM 和webpack 的基础使用
- Python list sort方法的具体使用
- 【阿里云镜像】使用阿里巴巴DNS镜像源——DNS配置教程
- 在Android中扫描wifi热点演示实例教程
- Android(安卓)代码设置Color的几种方式
- JsonObject和Gson详解
- android单元测试用例和日志输出
- android使用ant编译打包