synchronized之线程安全
一、当两个并发线程访问同一个对象object中的
这个synchronized(this)同步代码块时,
一个时间内只能有一个线程得到执行。
另一个线程必须等待当前线程执行完
这个代码块以后才能执行该代码块。
@SuppressLint("SimpleDateFormat")publicclassMainActivityextendsActivityimplementsOnClickListener{privateThreadmThraed;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);mThraed=newThread(mRunnable);((Button)findViewById(R.id.button1)).setOnClickListener(this);((Button)findViewById(R.id.button2)).setOnClickListener(this);}privateRunnablemRunnable=newRunnable(){@Overridepublicvoidrun(){/***线程安全*对线程进行加锁处理*线程内的数据处理完毕后,再开锁**/synchronized(mHandler){while(true){if(mThraed==null){break;}try{Thread.sleep(1000);mHandler.sendEmptyMessage(0x01);}catch(Exceptione){e.printStackTrace();}}}}};@SuppressLint("HandlerLeak")privateHandlermHandler=newHandler(){publicvoidhandleMessage(Messagemsg){switch(msg.what){case0x01:refreshUI();break;default:break;}}};privatevoidrefreshUI(){SimpleDateFormatsdf=newSimpleDateFormat("yyyy-MM-ddhh:mm:ss");Stringdate=sdf.format(newDate());Log.v("result",date);((TextView)findViewById(R.id.textView1)).setText(date);}@OverridepublicvoidonClick(Viewarg0){if(arg0.getId()==R.id.button1){if(mThraed==null){mThraed=newThread(mRunnable);mThraed.start();}else{mThraed=newThread(mRunnable);mThraed.start();}}if(arg0.getId()==R.id.button2){mThraed=null;}}}
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。