Android 线程同步 ConditionVariable的用法

版权声明:本文为匆忙拥挤repeat(stone)原创文章,转载请注明出处 —— http://blog.csdn.net/jjwwmlp456 https://blog.csdn.net/jjwwmlp456/article/details/18839757
import android.app.Activity;
import android.os.Bundle;
import android.os.ConditionVariable;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;


public class MainActivity extends Activity {
	ConditionVariable mCV = new ConditionVariable();
	Button unLock;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		
		unLock = (Button) findViewById(R.id.btn_unlock);
		new Thread() {
			public void run() {
				try {
					for (int i = 0; i < 5; i++) {
						Thread.sleep(1000);
						System.out.println(Thread.currentThread().getId() + ",count=" + i);
						if (i == 3) {
							mCV.close();//重置阻塞条件,当再次运行到block()时 仍会再次阻塞; 若不重置,则不再阻塞
							mCV.block();//当前线程阻塞,直到open() 
							System.out.println("block");
						}
						if (i == 4) {
							mCV.close();
							mCV.block(3000);//当前线程阻塞,直到open() 或 超时
							System.out.println("block 3 seconds");
							i = -1;
						}
					}
				} catch (InterruptedException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			};
		}.start();
		
		unLock.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View view) {
				mCV.open(); //打开即唤醒 阻塞线程
			}
		});
		
	}

}

没有更多推荐了,返回首页