JAVA多執行緒設計4個執行緒,其中兩個執行緒每次對j增加1,另外兩個執行緒對j每次減少1。
阿新 • • 發佈:2019-09-14
最新在看一些執行緒方面的問題,也找一些題目來練手,看到一套題,JAVA設計4個執行緒,其中兩個執行緒每次對j增加1,另外兩個執行緒對j每次減少1,寫出程式程式碼。由題目可以看出,並沒有要求面試者實現同步通訊,這類題還是比較簡單的,實現互斥就行了。
package com.study;
public class Demo001 {
// 操作的目標屬性J
private int j = 0;
public static void main(String[] args) {
Demo001 demo = new Demo001();
final OutPutClass putPutClass = demo.new OutPutClass();
for (int index = 0; index < 2; index++) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
putPutClass.ins();
}
});
thread.start();
}
for (int index = 0; index < 2; index++) {
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
putPutClass.des();
}
});
thread2.start();
}
}
class OutPutClass {
public synchronized void ins() {
j++;
System.out.println("當前執行緒【" + Thread.currentThread().getName() + "】正在對J進行遞增,結果為:" + j);
}
public synchronized void des() {
j--;
System.out.println("當前執行緒【" + Thread.currentThread().getName() + "】正在對J進行遞減,結果為:" + j);
}
}
}