Skip to content

Instantly share code, notes, and snippets.

@benaryorg
Last active September 3, 2015 22:05
Show Gist options
  • Save benaryorg/f7c174c53efaba4d8575 to your computer and use it in GitHub Desktop.
Save benaryorg/f7c174c53efaba4d8575 to your computer and use it in GitHub Desktop.
import java.util.*;
public class AsyncPrinter extends Thread
{
private Queue<String> queue;
public AsyncPrinter()
{
this.queue=new LinkedList<>();
this.setDaemon(true);
this.start();
}
public void run()
{
String name;
while(true)
{
while((name=this.queue.poll())!=null)
{
System.out.print("Hello, ");
System.out.println(name);
}
try
{
this.wait();
}
catch(Exception ex)
{
}
}
}
public boolean add(String name)
{
boolean ret=queue.offer(name);
try
{
this.notifyAll();
}
catch(IllegalMonitorStateException ex)
{
}
return ret;
}
public static void main(String... args)
{
AsyncPrinter printer=new AsyncPrinter();
printer.add("Alan");
}
}
@Deleplace
Copy link

For the demo, how about this.setDaemon(false); ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment