Skip to content

Instantly share code, notes, and snippets.

@maxbisesi
Last active July 19, 2017 16:18
Show Gist options
  • Save maxbisesi/98b3d641af1519c959e82dcee995097b to your computer and use it in GitHub Desktop.
Save maxbisesi/98b3d641af1519c959e82dcee995097b to your computer and use it in GitHub Desktop.
Shows the proper concurrent use of a LinkedTransferQueue
public class Hello {
public static void main(String[] args){
Library library = new Library();
new Thread(library).start();
new Thread(new Renter(library,"Mike")).start();
new Thread(new Renter(library,"Max")).start();
new Thread(new Renter(library,"Priebe")).start();
new Thread(new Renter(library,"Dom")).start();
}
}
class Library implements Runnable{
private TransferQueue<Book> shelves = new LinkedTransferQueue<>();
public Library() {
shelves.add(new Book("Capulets and Montagues, the unknown link"));
shelves.add(new Book("War What is it Good For"));
shelves.add(new Book("Virtuous Villians"));
shelves.add(new Book("Love in the Water"));
}
public void run(){
while(true){ }
}
public Book lend(){
try {
Book book = shelves.take();
System.out.println("This ones good try "+book.getName()+". Enjoy!");
return book;
} catch(InterruptedException e){ }
return new Book("Free Library Pamphlet on plagarism");
}
public void accept(Book book){
shelves.offer(book);
}
}
class Renter implements Runnable {
private Library lib;
private String name;
public Renter(Library lib,String x){
name = x;
this.lib = lib;
}
public void run(){
while(true){
Book book = lib.lend();
System.out.println(name+" chekced out "+book.getName());
try{
Thread.sleep(ThreadLocalRandom.current().nextInt(1000,5000));
} catch(InterruptedException e) { }
System.out.println(name+": Im done with "+book.getName()+" here take it back!");
lib.accept(book);
}
}
}
class Book{
private String name;
public Book(String x ){
name = x;
}
public String getName(){
return name;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment