Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package lab3;
- import java.util.List;
- import java.util.ArrayList;
- import java.util.List;
- import java.util.concurrent.Callable;
- import java.util.concurrent.ExecutionException;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.Future;
- import java.util.concurrent.locks.Condition;
- import java.util.concurrent.locks.Lock;
- import java.util.concurrent.locks.ReentrantLock;
- class Bilet{
- int numer; // numer biletu
- boolean czyZarezerwowany = false; // false - nie, true - tak
- Lock lock = new ReentrantLock();
- Condition biletZarezerwowany = lock.newCondition();
- Condition biletZwolniony = lock.newCondition();
- // konstruktor
- Bilet(int n){
- numer= n;
- }
- //Metoda rezerwująca bilet
- void zarezerwuj() {
- lock.lock();
- try {
- while (czyZarezerwowany == true)
- biletZarezerwowany.await();
- czyZarezerwowany = true;
- System.out.println("Wątek: " + Thread.currentThread().getName() + " zarezerwował bilet: " + numer);
- biletZwolniony.signal();
- } catch(InterruptedException exc) {
- } finally {
- lock.unlock();
- }
- }
- //Metoda zwalniająca bilet
- void zwolnij() {
- lock.lock();
- try {
- while (czyZarezerwowany == false)
- biletZwolniony.await();
- czyZarezerwowany = false;
- System.out.println("Wątek: " + Thread.currentThread().getName() + " zwolnił bilet: " + numer);
- biletZarezerwowany.signal();
- } catch(InterruptedException exc) {
- } finally {
- lock.unlock();
- }
- }
- }
- class Kupiec implements Callable<Integer>{
- List<Bilet> bilety;
- Kupiec(List<Bilet> b) {
- bilety = b;
- }
- public Integer call() {
- for (int i = 0; i < 10; i++) {
- for(int j = 0; j < bilety.size(); j++) {
- bilety.get(j).zarezerwuj();
- try { // autor zastanawia się chwilę co napisać
- Thread.sleep((int) (Math.random()* 10000));
- } catch (InterruptedException exc) {
- }
- bilety.get(j).zwolnij();
- }
- }
- return 1;
- }
- }
- public class Zadaniee {
- public static int wykonuj(ExecutorService exec, List<Callable<Integer>> tasks) throws Exception{
- List<Future<Integer>> results = exec.invokeAll(tasks);
- return 1;
- }
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- List<Bilet> bilety = new ArrayList<Bilet>();
- bilety.add(new Bilet(1));
- bilety.add(new Bilet(2));
- bilety.add(new Bilet(3));
- List<Callable<Integer>> kupcy = new ArrayList<Callable<Integer>>();
- ExecutorService exec = Executors.newFixedThreadPool(6);
- kupcy.add(new Kupiec(bilety));
- kupcy.add(new Kupiec(bilety));
- kupcy.add(new Kupiec(bilety));
- kupcy.add(new Kupiec(bilety));
- kupcy.add(new Kupiec(bilety));
- kupcy.add(new Kupiec(bilety));
- try {
- int result = wykonuj(exec, kupcy);
- exec.shutdown();
- } catch(Exception exc) {
- exc.printStackTrace();
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement