Java AtomicInteger extend

Description

Java AtomicInteger extend

import java.util.concurrent.atomic.AtomicInteger;

class TaskCounter extends AtomicInteger {

  private int maxNumber;
  
  public TaskCounter(int maxNumber){
    super.set(0);
    this.maxNumber=maxNumber;
  }/*  www.  j  av  a2 s .c om*/
  public boolean taskAdd() {
    while (true) {
      int value=super.get();
      if (value==maxNumber) {
        System.out.printf("The task pool is full.\n");
        return false;
      } else {
        int newValue=value+1;
        boolean changed=super.compareAndSet(value,newValue);
        if (changed) {
          System.out.printf("new task\n");
          return true;
        }
      }
    }
  }
  public boolean taskComplete() {
    while (true) {
      int value=super.get();
      if (value==0) {
        System.out.printf("The task pool is empty.\n");
        return false;
      } else {
        int newValue=value-1;
        boolean changed=super.compareAndSet(value,newValue);
        if (changed) {
          System.out.printf("task finished\n");
          return true;
        }
      }
    }
  }

}
 class Tester implements Runnable {
  private TaskCounter counter;
  public Tester(TaskCounter counter) {
    this.counter=counter;
  }
  @Override
  public void run() {
    counter.taskAdd();
    counter.taskComplete();
    counter.taskComplete();
    counter.taskAdd();
    counter.taskAdd();
    counter.taskAdd();
    counter.taskAdd();
    counter.taskAdd();
    counter.taskAdd();
  }

}
 class Developer implements Runnable {
  private TaskCounter counter;
  public Developer(TaskCounter counter) {
    this.counter=counter;
  }
  @Override
  public void run() {
    counter.taskAdd();
    counter.taskAdd();
    counter.taskAdd();
    counter.taskAdd();
    counter.taskComplete();
    counter.taskComplete();
    counter.taskComplete();
    counter.taskAdd();
    counter.taskAdd();
    counter.taskAdd();
  }
}

public class Main {
  public static void main(String[] args) throws Exception{
    TaskCounter counter=new TaskCounter(5);
    Developer sensor1=new Developer(counter);
    Tester sensor2=new Tester(counter);
    
    Thread thread1=new Thread(sensor1);
    Thread thread2=new Thread(sensor2);
    
    thread1.start();
    thread2.start();
    thread1.join();
    thread2.join();
    System.out.printf("Main: Number of tasks: %d\n",counter.get());
  }
}



PreviousNext

Related