3
我正在嘗試製作一個解決併發問題的android應用程序示例,但對我而言,我的代碼顯示正確的結果而不是由競態條件導致的錯誤結果是奇怪的。以下是我的代碼,我讀到認爲在Java中Android上的Java併發性
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
public class MainActivity extends Activity {
private breadBaker bB;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Log.d("shanwu","Thread Test Starts!");
bB = new breadBaker();
bB.makeBread();
breadBuyer TA = new breadBuyer();
try{
Thread a =new Thread(TA);
Thread b =new Thread(TA);
Thread c =new Thread(TA);
Thread d =new Thread(TA);
Thread e =new Thread(TA);
Thread f =new Thread(TA);
Thread g =new Thread(TA);
Thread h =new Thread(TA);
Thread i =new Thread(TA);
Thread j =new Thread(TA);
a.start();
b.start();
c.start();
d.start();
e.start();
f.start();
g.start();
h.start();
i.start();
j.start();
bB.makeBread();
}catch(Exception e){
e.printStackTrace();
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
class breadBaker{
private int breadCount;
public breadBaker(){
breadCount = 3;
}
public void makeBread(){
breadCount++;
Log.d("shanwu","make one bread, current bread count: "+breadCount);
}
public void giveBread(){
breadCount--;
Log.d("shanwu","sold one bread, current bread count: "+breadCount);
}
public int getBreadCount()
{
return breadCount;
}
}
class breadBuyer implements Runnable{
public void buyBread(){
bB.giveBread();
}
public void waitInLine(){
// Thread.Sleep(100);
}
@Override
public void run() {
// TODO Auto-generated method stub
if(bB.getBreadCount() > 0){
buyBread();
}
else
{
waitInLine();
}
}
}
}
我基本上是從Java中想到的內容學習,並努力使之適用於Android(1150頁左右)...請指出什麼似乎成爲問題,我認爲breadcount會由於競爭條件而變成負值,但它不是,它工作正常...
恩,你真的只做一個麪包,然後期望它失敗嗎?競爭條件*可能會發生,它們不會一直髮生,這是對他們的全部刺激。 –
你的線程餓死了:P –
不錯的一個貓頭鷹 –