问题 :-
使用 Java,您将如何允许多个线程同时在临界区运行,但上限为 6。不应超过 6 个线程同时访问该线程。
我感觉我所做的解决方案(如下所示)是错误的,因为由于synchronized关键字,只有一个线程可以访问关键部分。如果可能的话,请任何人确认并发布其他解决方案。
我的解决方案
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();
}
}
}
}