信号量应用--操场跑道问题

package com.multithread;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * created on 7/26/2018
 * Used for if one playground has 5 track, we have several students, how to handle
 */
public class TestSemphore {

  private static Playground playgroud = new Playground();


  public static void main(String[] args)throws InterruptedException {
    ExecutorService service = Executors.newCachedThreadPool();
    for (int i = 0 ; i < 200; i ++) {
      Playground.Track track = playgroud.getTrack();
      service.submit(new Student("name" + i));
      playgroud.releaseTrack(track);
    }
  }

  static class Student implements Runnable {
    private String name;
    public Student(String name) {
      this.name = name;
    }

    @Override
    public void run() {
      System.out.println("student " + name  + " is running");
    }
  }
}

class Playground {
  private Map trackMap = new HashMap<>();
  private Semaphore semphore = new Semaphore(5, true);


  private void initPlayground () {
    for (int i =0 ; i < 5; i ++){
      trackMap.put(new Track(i), false);
    }
  }

  public Playground() {
    initPlayground();
  }

  public Track getTrack() throws InterruptedException {
    semphore.tryAcquire();
    for (Map.Entry entry : trackMap.entrySet()) {
      Track track = entry.getKey();
      Boolean used = entry.getValue();
      if(!used) {
        entry.setValue(true);
        return track;
      }
    }
    return null;
  }

  public void releaseTrack(Track track) {
    trackMap.put(track, false);
    semphore.release();
  }


  class Track{
    int num;
    public Track(int num) {
        this.num= num;
    }

    @Override
    public String toString() {
      return "Track{" +
              "num=" + num +
              '}';
    }
  }
}
 

你可能感兴趣的:(信号量应用--操场跑道问题)