首页 > 代码库 > synchronized之线程安全

synchronized之线程安全

 一、当两个并发线程访问同一个对象object中的

这个synchronized(this)同步代码块时,

一个时间内只能有一个线程得到执行。

另一个线程必须等待当前线程执行完

这个代码块以后才能执行该代码块。 

@SuppressLint("SimpleDateFormat")
public class MainActivity extends Activity implements OnClickListener{
private Thread mThraed;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mThraed = new Thread(mRunnable);
((Button)findViewById(R.id.button1)).setOnClickListener(this);
((Button)findViewById(R.id.button2)).setOnClickListener(this);
}
private Runnable mRunnable = new Runnable(){
@Override
public void run() {
/**
 * 线程安全
 * 对线程进行加锁处理
 * 线程内的数据处理完毕后,再开锁
 * */
synchronized(mHandler){
while(true){
if(mThraed == null){
break;
}
try{
Thread.sleep(1000);
mHandler.sendEmptyMessage(0x01);
}catch(Exception e){
e.printStackTrace();
}
}
}
}
};
@SuppressLint("HandlerLeak")
private Handler mHandler = new Handler(){
public void handleMessage(Message msg){
switch(msg.what){
case 0x01:
refreshUI();
break;
default:
break;
}
}
};
private void refreshUI(){
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String date = sdf.format(new Date());
Log.v("result",date);
((TextView)findViewById(R.id.textView1)).setText(date);
}
@Override
public void onClick(View arg0) {
if(arg0.getId() == R.id.button1){
if(mThraed == null){
mThraed = new Thread(mRunnable);
mThraed.start();
}else{
mThraed = new Thread(mRunnable);
mThraed.start();
}
}
if(arg0.getId() == R.id.button2){
mThraed = null;
}
}
}


本文出自 “爬过山见过海” 博客,请务必保留此出处http://670176656.blog.51cto.com/4500575/1548283

synchronized之线程安全