Last active
September 3, 2015 22:05
-
-
Save benaryorg/f7c174c53efaba4d8575 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
For the demo, how about
this.setDaemon(false);
?