溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

synchronized之線程安全

發(fā)布時間:2020-07-06 21:52:54 來源:網(wǎng)絡(luò) 閱讀:486 作者:671076656 欄目:開發(fā)技術(shù)

 一、當(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;
}
}
}


向AI問一下細(xì)節(jié)

免責(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)容。

AI