用Java实现Multiplex(并发)

Aru*_*unM 1 java concurrency multithreading

题 :-

使用Java,您将如何允许多个线程同时在关键部分中运行,但上限为6。不应同时有6个以上的线程同时访问该线程。

我有一种感觉,该解决方案我做了(如下所示)是错误的,因为只有一个线程可以因为访问临界区同步关键字。请任何人确认这一点并发布其他解决方案(如果可能)。

我的解决方案


package multiplex;

public class Multiplex {

    private static Multiplex multiplex = new Multiplex();
    private volatile static int counter = 0;

    /**
     * @param args
     */
    public static void main(String[] args) {
        Runnable run = new Runnable() {
            @Override
            public void run() {
                try {
                    multiplex.criticalSection();
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        };
        for(int index = 0; index < 100; index++){
            Thread thread = new Thread(run);
            thread.setName("Multiplex"+index);
            thread.start();
        }

    }

    public void criticalSection() throws InterruptedException{
        System.out.println("counter is" + counter);
            synchronized (multiplex) {
                    if(counter <=5 ){
                    counter++;
                    System.out.println("No Counter is " + counter);
                    Thread.sleep(1000);
                    System.out.println(Thread.currentThread().getName() + "Hello I am critical");
                    multiplex.notify();

                }else{
                    counter--;
                    System.out.println("Waiting Thread" + Thread.currentThread().getName() + " " + counter);

                    multiplex.wait();
                }

            }
    }
}
Run Code Online (Sandbox Code Playgroud)

fge*_*fge 5

解决方案是使用Semaphore

// nrPermits is the number of simultaneous semaphore holders
final Semaphore semaphore = new Semaphore(nrPermits);

// then:

semaphore.acquire(); // blocks until a permit is available
try {
    criticalSection();
} finally {
    semaphore.release();
}
Run Code Online (Sandbox Code Playgroud)

另一种解决方案是使用bounded ThreadPool和策略在线程池已满时暂停任务。这是Executors.newFixedThreadPool()默认情况下的功能:

final ExecutorService service = Executors.newFixedThreadPool(nrTasks);
// use Runnables or FutureTasks if the threads produce results
Run Code Online (Sandbox Code Playgroud)