Я читал о Semaphore , Counting Semaphore
и, основываясь на документации, он говорит, что цель Semaphore
- предоставить доступ к множественным потокам к некоторым общему ресурсу , в в то же время .
Я попытался найти в Интернете конкретный пример, но не нашел.
Я придумал сценарий, в котором Person / thread
просматривает mov ie. Теперь Cinema hall
может моделировать shared resource
, который может одновременно использоваться multiple persons , threads
. Я чувствовал, что это будет хорошим примером для общения.
В этом квесте я создал следующую программу.
Entry. java
package com.example.threads.semaphore.second.v2;
import java.util.concurrent.Semaphore;
// This is the main "Entry" for thread
// which want to watch movie.
public class Entry {
// Counting semaphore, with capacity 2
// which means at most, 2 persons/ threads
// will go into threatre.
private Semaphore available = new Semaphore(2, true);
private MovieWatching mw = new MovieWatching(available);
// This method will allow person to go inside Cinema hall
// by first trying to acquire semaphore.
// The logic of person getting out of theatre
// is dependent upon the Person itself, which we set in Main thread,
// The flag -> "moveOut"
public void access(Person p) throws InterruptedException {
// This will consume a permit.
available.acquire();
System.out.println("Person " + p + " allowed to inside theatre");
mw.watchMovie(p);
}
}
Человек. java
package com.example.threads.semaphore.second.v2;
public class Person implements Runnable {
// This thread local would be used to make
// person go out of theatre, and thus other
// person can go inside the Theatre, who are trying to acquire a Semaphore.
// Here Theatre represents a shared resource.
private Entry entry;
public Person(Entry entry) {
this.entry = entry;
}
// This needs to be volatile as this field
// is being update in main thread.
// This simulated field visibility problem
// when this isn't kept as volatile, then
// the for(;;) loop in MovieWatching() mehthod
// never comes out.
private volatile Boolean moveOut = new Boolean(false);
public Boolean getMoveOut() {
return moveOut;
}
public void setMoveOut(Boolean moveOut) {
this.moveOut = moveOut;
}
@Override
public void run() {
try {
entry.access(this);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
MovieWatching. java: Представляет угрозу / mov ie просмотр.
package com.example.threads.semaphore.second.v2;
import java.util.concurrent.Semaphore;
public class MovieWatching {
private Semaphore available;
public MovieWatching(Semaphore available) {
this.available = available;
}
public void watchMovie(Person p) {
for (; !p.getMoveOut();) {
// Movie watcing activity
// unless person decides to go in the middle
// the person will keep watching movie.
}
System.out.println("Person " + p + " going out now");
// Now, make room for other waiting threads
// who want to watch movie, waiting at Entry.
available.release();
}
}
MainDemo. java: Основная точка входа.
package com.example.threads.semaphore.second.v2;
public class MainDemo {
public static void main(String[] args) throws InterruptedException {
Entry entry = new Entry();
Person p1 = new Person(entry);
Person p2 = new Person(entry);
Person p3 = new Person(entry);
Thread t1 = new Thread(p1);
Thread t2 = new Thread(p2);
Thread t3 = new Thread(p3);
t1.start();
t2.start();
// Making sure that t1 and t2 gets
// into theatre.
Thread.sleep(1000);
t3.start();
Thread.sleep(10000);
p1.setMoveOut(true);
t1.join();
t2.join();
t3.join();
}
}
Кажется, эта программа работает, как я и ожидал, пример:
Person com.example.threads.semaphore.second.v2.Person@67ac2678 allowed to inside theatre
Person com.example.threads.semaphore.second.v2.Person@2204de0a allowed to inside theatre
Person com.example.threads.semaphore.second.v2.Person@67ac2678 going out now
Person com.example.threads.semaphore.second.v2.Person@7b2d84bd allowed to inside theatre
У меня есть использовал Semaphore
первый раз, поэтому хочу спросить экспертов, это то, что ожидается от Semaphore
, и правильна ли моя реализация (для имитации Semaphore
предоставления access to multiple threads
для shared resource
)