我試圖使用兩個線程打印一個同步的Integer對象(mInt)直到10.但是其中一個線程鎖定另一個線程會拋出下面粘貼的異常。有人可以在這裏指出我的錯誤。這是更多的Java相關的問題,但包括「android」標籤,因爲我已經爲android編碼它,我需要嘗試在它的某個時間。嘗試從共享資源打印偶數和奇數
09-24 15:24:17.198 10621-11400/com.sameer.android.samplecode E/AndroidRuntime:致命異常:線程364 工藝:com.sameer.android.samplecode,PID:10621 java.lang.IllegalMonitorStateException:通過notify()之前的線程鎖定對象() at java.lang.Object.notify(Native Method) at com.sameer.android.samplecode.MainActivity $ Even.run(MainActivity.java:55 )
public class MainActivity extends AppCompatActivity {
private Integer mInt;
class Odd extends Thread {
private final String TAG = Odd.class.getSimpleName();
@Override
public void run() {
Log.i(TAG, "Odd() Started....");
synchronized (mInt) {
try {
while (mInt <= 10)
{
while (mInt % 2 != 1) {
Log.i(TAG, "Odd... Looping " + mInt);
mInt.wait();
}
mInt++;
Log.i(TAG, "Odd " + mInt);
mInt.notify();
}
}
catch (InterruptedException e) {
Log.e(TAG, "Odd() " + e.getMessage());
}
}
Log.i(TAG, "Odd() Ended....");
}
}
class Even extends Thread {
private final String TAG = Even.class.getSimpleName();
@Override
public void run() {
Log.i(TAG, "Even() Started....");
synchronized (mInt) {
try {
while (mInt <= 10)
{
while (mInt % 2 != 0) {
Log.i(TAG, "Even... Looping " + mInt);
mInt.wait();
}
mInt++;
Log.i(TAG, "Even " + mInt);
mInt.notify();
}
}
catch (InterruptedException e) {
Log.e(TAG, "Even() " + e.getMessage());
}
}
Log.i(TAG, "Even() Ended....");
}
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mInt = new Integer(0);
Button button = (Button) findViewById(R.id.button);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Even even = new Even();
even.start();
Odd odd = new Odd();
odd.start();
}
});
}
}
嘿馬蒂亞斯,你的第一段與我有關。感謝您的評論。 – Sameer
我覺得你也應該編輯第二段。我可能誤導別人。 – Sameer