Android UI线程和子线程使用synchronized,UI线程阻塞但无法获取锁
使用AudioRecord录音时,需要在UI线程的StopRecord方法、数据读取线程的while代码块之间加上锁,我使用了synchronized(byte[])。 但是按下停止录音按钮之后,StopRecord被阻塞了,while代码块却仍然在循环执行。
下面是抽象出来的简单代码,可以直接运行,同样出现了UI线程阻塞但无法获取锁的结果:
public class MainActivity extends ActionBarActivity implements View.OnClickListener{
final byte[] lock = new byte[0];
boolean isRecording = false;
RecorderThread recorderThread;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button buttonStart = (Button)findViewById(R.id.button_start);
Button buttonStop = (Button)findViewById(R.id.button_stop);
buttonStart.setOnClickListener(this);
buttonStop.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button_start:
if(!isRecording){
// Initialize AudioRecord and startRecording
isRecording = true;
recorderThread = new RecorderThread();
recorderThread.start();
}
break;
case R.id.button_stop:
if(isRecording){
synchronized (lock){
// Stop AudioRecord and release
isRecording = false;
}
}
break;
}
}
private class RecorderThread extends Thread{
@Override
public void run() {
while (isRecording){
synchronized (lock){
try{
// AudioRecord.read()
Thread.sleep(200);
Log.d("TAG","read a sample data");
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
}
}
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
android:id="@+id/button_start"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Start"/>
android:id="@+id/button_stop"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Stop"/>
相关阅读:
c3p0一个数据源多用户问题
javascript获取上传图片大小不一致帮我看下 代码如下
android 小米手机用第三方登陆qq,授权之后请求参数不规范?
IOS 中使用socket建立TCP连接远程获取图片
为什么我用pod添加一个第三方库后工程会报错呢?
obj.currentStyle.left与obj.offsetLeft
请教一些ReactNative的一些基础知识。
centos用npm安装forever失败
嵌套ViewPager,调用其setCurrentItem方法失效
线程暂停和唤醒的问题
像GOOGLE BAIDU神马的cache hit rate一般多少啊?
MongoDB如何正确插入带双引号的文本记录??
为什么我的centos搭建好的php环境,新建了虚拟网站,可以访问html,不能访问php?
ArrayList的实现与List接口如何理解
shell脚本的问题
Android端对端视频流播放
读研期间,云存储这个研究方向怎么样?
百度(ueditor)编辑器输出乱码?
关于网站换皮肤的功能,谁可以告诉下mac.pcbeta.com 它的换肤原理?
怎么让苹果应用 plist服务器不缓存文件