編輯:Android開發教程
為什麼會有線程同步的概念呢?為什麼要同步?什麼是線程同步?先看一段代碼:
package com.maso.test;
public class ThreadTest2 implements Runnable{
private TestObj testObj = new TestObj();
public static void main(String[] args) {
ThreadTest2 tt = new ThreadTest2();
Thread t1 = new Thread(tt, "thread_1");
Thread t2 = new Thread(tt, "thread_2");
t1.start();
t2.start();
}
@Override
public void run() {
for(int j = 0; j < 10; j++){
int i = fix(1);
try {
Thread.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " : i = " + i);
}
}
public int fix(int y){
return testObj.fix(y);
}
public class TestObj{
int x = 10;
public int fix(int y){
return x = x - y;
}
}
}
輸出結果後,就會發現變量x被兩個線程同時操作,這樣就很容易導致誤操作。如何才能解決這個問題呢?用線程的同步技術,加上synchronized關鍵字
public synchronized int fix(int y){
return testObj.fix(y);
}
加上同步後,就可以看到有序的從9輸出到-10.
如果加到TestObj類的fix方法上能不能實現同步呢?
public class TestObj{
int x = 10;
public synchronized int fix(int y){
return x = x - y;
}
}
如果將synchronized加到方法上則等價於
synchronized(this){
}
Android屬性動畫之實現布局的下拉展開
前段時間,我們做了一下Android的幾個動畫(http://blog.csdn.net/qq_25193681/article/details/51777248),對A
Linux下如何編譯Android-VLC開源播放器
這兩天需要做音視頻播放相關的東西,所以重新找了目前android下的解碼庫。Android自帶的解碼庫支持不全,因此很多第三方播放器都是自帶解碼器,絕大部分都是使用FFM
Android推送服務:百度雲推送
一、推送服務簡介消息推送,顧名思義,是由一方主動發起,而另一方與發起方以某一種方式建立連接並接收消息。在Android開發中,這裡的發起方我們把它叫做推送服務器(Push
Android滑動效果基礎篇(三) Gallery仿圖像集浏覽
Android系統自帶一個Gallery浏覽圖片的應用,通過手指拖動時能夠非常流暢的顯示圖片,用戶交互和體驗都很好。本示例就是通過Gallery和自定義的View,模仿實