java线程面试题2

    技术2022-05-13  0

    设计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--);  } }


    最新回复(0)