设计4个线程,其中两个线程每次对j增加1,另外两个线程对j每次减少1。写出程序。
public static void main(String[] args) { // new InterviewQuestionTest().init(); new InterviewQuestionTest().init2(); }
private void init2() { final Business2 business = new Business2(); for (int i = 0; i < 2; i++) { new Thread() { public void run() { business.increament(); } }.start();
new Thread() { public void run() { business.decreament(); } }.start(); } }
class Business2 { int j = 0;
public synchronized void increament() { System.out.println(Thread.currentThread().getName() + " increament: " + j++); }
public synchronized void decreament() { System.out.println(Thread.currentThread().getName() + " decreament: " + j--); } }