将多线程中的函数放入单个队列中

时间:2015-04-25 13:16:07

标签: java multithreading

我正在创建一个图书馆模拟器,里面有一个图书馆,一个图书管理员和多个借阅者对象。它涉及多个借用者线程和一个同时运行的图书管理员线程,执行诸如请求书籍,还书等任务。

我一直在使用同步功能来确保每个借款人内部的功能不会变得混乱,但现在我试图弄清楚,一旦借款人开始一个功能,将其放入一个带有集合的队列中在条目之间休眠,并且输出将在间隔内发布到控制台。

我的问题是,一旦借款人获得了一个功能,例如RequestBooks,而不是简单地将它输出到控制台,并且由于存在多个借用者的事实,有什么方法可以将函数的输出或Borrower在队列中执行该函数,所以,比方说,每隔3秒,队列处理一个条目,然后运行该函数,以便放入队列的每个函数的输出以偶数间隔打印出来。

在某些时候,我将使用一个Lock系统(我也不确定如何执行多个线程),这将决定哪个借用者向队列发送一个函数,如果这有助于任何混淆。

借款人代码如下:

public class Borrower extends Thread {

private int noOfBooks;
private Set<Book> BooksBorrowed;
private Set<Integer> booksRequested;
private int id;
private int runs;
private Library library;
private Random randSleep = new Random();

public Borrower(int id, Library library, int runs) {

    this.library = library;
    this.id = id;
    this.runs = runs;
    noOfBooks = 1;

    }

public Borrower(){}

public String getLoans() {
    String output = "";
    for(Book b : BooksBorrowed) {
        output +=" "+b.getBookId()+" ";
    }
    return output;
}

public void run()
{   
    try {
        Initialize();

        for(int i = 0; i < runs; i++) {
            RequestBooks();
            ReturnBooks();
        }

    } finally {}
}

public synchronized void Initialize() {

    int min = 1;
    int max = 10;
    Random r = new Random();
    noOfBooks = r.nextInt(max - min + 1) + min;

    System.out.println("--------------------------");
    System.out.println("Borrower "+id+" Starting");

    notifyAll();
}

public synchronized void RequestBooks () {

    Random r2 = new Random();
    Book temp = null;

    ArrayList<Book>books = new ArrayList<Book>(library.getBooks());
    ArrayList<Integer>Chosen = new ArrayList<Integer>();

    for(int i = 0; i < noOfBooks; i++){
        int index = r2.nextInt(books.size());
        temp = books.get(index);
        int tempId = temp.getBookId();
        Chosen.add(tempId);
    }
    System.out.println("--------------------------");
    System.out.println("\nBorrower "+id+" requests " +noOfBooks+" Books from Library ");

    booksRequested = new HashSet<Integer>(Chosen);

    String requestedBooks = "";

    for(Integer bookid : Chosen) {
        requestedBooks = requestedBooks+bookid+" ";
        booksRequested.add(bookid);

    }
    System.out.println("Borrower "+id+" request Books: "+requestedBooks);

    BooksBorrowed = library.RQST(id,booksRequested);
    ArrayList<Book> chosenBooks = new ArrayList<Book>();
    chosenBooks.addAll(BooksBorrowed);

    System.out.println("Books requested by Borrower "+id+" : "+requestedBooks+"\n");

    String receivedBooks = "";
    Book[]BookArray = BooksBorrowed.toArray(new Book[BooksBorrowed.size()]);
    for(Book b : BookArray) {
        receivedBooks = receivedBooks+b.getBookId()+" ";
    }

    System.out.println("Borrower "+id+" Books recieved :"+receivedBooks);
    System.out.println("--------------------------");
    notifyAll();

}

public synchronized void ReturnBooks() {
    Set<Integer> BooksReturned;
    ArrayList<Integer> returningBooks = new ArrayList<Integer>();
    String returnedBooks = "";
    ArrayList<Book> borrowed = new ArrayList<Book>(BooksBorrowed);

    for (Book b : borrowed) {
        returningBooks.add(b.getBookId());
        returnedBooks = returnedBooks+b.getBookId()+" ";
    }

    BooksReturned = new HashSet<Integer>(returningBooks);

    library.RTRN(BooksReturned);
    System.out.println("\nBorrower "+id+" returned books to library: "+returnedBooks+"\n");
}   

这是图书管理员代码:

public class Librarian extends Thread {

Library library;
int runs = 0;

public Librarian(Library library, int runs) {
    this.library = library;
    this.runs = runs;

}
public ArrayList<Book> AddBooks() {  
    ArrayList<Book> addbooks = new ArrayList<Book>();

    addbooks.add(new Book("The Lord of the Rings, The Fellowship",1,5));
    addbooks.add(new Book("The Lord of the Rings, Two Towers",2,5));
    addbooks.add(new Book("The Lord of the Rings, Return of King",3,5));
    addbooks.add(new Book("The Hunger Games",4,5));
    addbooks.add(new Book("A Game of Thrones",5,5));
    addbooks.add(new Book("Storm of Swords",6,5));
    addbooks.add(new Book("The Eagles Lair",7,5));
    addbooks.add(new Book("The Philosophers Stone",8,5));
    addbooks.add(new Book("Programming in Java",9,2));
    addbooks.add(new Book("Hit and Run",10,5));
    addbooks.add(new Book("The man in the Iron Mask",11,5));
    addbooks.add(new Book("A Dance With Dragons",12,5));
    addbooks.add(new Book("A Feast for Crows",13,5));
    addbooks.add(new Book("Jack the Ripper",14,1));
    addbooks.add(new Book("The Oddessey",15,1));

    return addbooks;


}
@Override
public void run() {
    try {
        //Random rsleep = new Random();
        Initialize();

    for(int i = 0;i < runs; i++) {

        //sleep(rsleep.nextInt(10000));
        getBorrowers();
    }

    } catch(Exception e){}
}

public void Initialize(){
    System.out.println("\nStarting Librarian");
    System.out.println("Library Initializing\n");
}

public void LibraryStatus() {

}

public void getBorrowers() {
    System.out.println("\nGetting Current Borrowers\n");
    String BorrowedBooks ="";
    Set<Entry<Integer,Set<Book>>> tempset = library.getBorrowers().entrySet();
    for(Entry<Integer,Set<Book>> entry : tempset) {

        for(Book b : entry.getValue()) {
            BorrowedBooks = BorrowedBooks + b.toString()+""; 
        }

        System.out.println("Borrower "+entry.getKey()+" borrowed books : "+BorrowedBooks);
        BorrowedBooks ="";
    }
}

public void setLibrary(Library library2) {
    this.library = library2;

}   

}

以下是控制其他人的主要课程:

public class LibraryModel {

Library library = new Library();
Librarian librarian;
ArrayList<Borrower> BorrowArray = new ArrayList<Borrower>();
int runs = 0;
int isFinished;
Boolean isActive = true;


public LibraryModel() {
    library.AddBooks();

}

public static void main(String[]args) 
{
    int borrowCount = 0;
    System.out.println("Welcome to the Library Simulator\n");


    LibraryModel model = new LibraryModel();

    char quit = 'y';
    Scanner sc = new Scanner(System.in);

    while(quit != 'q')  {
        System.out.println("\n[S = start, A = About, Q = quit]");

        String a = sc.next();

        switch (a) {

            case "S":
                model.isActive = true;
                System.out.println("Please enter the number of Borrowers\n");
                borrowCount = sc.nextInt();
                System.out.println("Please enter how many runs the Program will run");
                model.runs = sc.nextInt();
                model.isFinished = model.runs;

                model.librarian = new Librarian(model.library,model.runs);


                    for(int i = 0 ;i < borrowCount; i++) {
                        model.getBorrowers().add(new Borrower(i+1,model.getLibrary(),model.runs));
                    }
                    model.librarian().start();

                    for(Borrower b : model.getBorrowers()) {
                        b.start();
                    }

                    try {
                model.librarian.join();
                for(Borrower b : model.getBorrowers()) {
                    b.join();
                }
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            break;

            case "A":
                break;

            case "Q" :
                quit = 'q';
                break;

            default :
                System.out.println("Incorrect Entry, please enter a correct");
                break;
            }
    }   
}

public Library getLibrary() {
    return library;
}

public ArrayList<Borrower> getBorrowers() {
    return BorrowArray;
}

public Librarian librarian() {
    return librarian;
}


public int runs() {
    return runs;
}

}

提前感谢您的帮助

0 个答案:

没有答案