最新在看一些線程方面的問題,也找一些題目來練手,看到一套題,JAVA設計4個線程,其中兩個線程每次對j增長1,另外兩個線程對j每次減小1,寫出程序代碼。由題目能夠看出,並無要求面試者實現同步通訊,這類題仍是比較簡單的,實現互斥就好了。java
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); } } }