您好,登錄后才能下訂單哦!
一、當(dāng)兩個并發(fā)線程訪問同一個對象object中的
這個synchronized(this)同步代碼塊時,
一個時間內(nèi)只能有一個線程得到執(zhí)行。
另一個線程必須等待當(dāng)前線程執(zhí)行完
這個代碼塊以后才能執(zhí)行該代碼塊。
@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() { /** * 線程安全 * 對線程進(jìn)行加鎖處理 * 線程內(nèi)的數(shù)據(jù)處理完畢后,再開鎖 * */ 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; } } }
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。