JAVA多线程设计4个线程,其中两个线程每次对j增长1,另外两个线程对j每次减小1。

最新在看一些线程方面的问题,也找一些题目来练手,看到一套题,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);
    }
  }
}
相关文章
相关标签/搜索