new Thread(Runnable target, String name)
/*
* Output:
*
* Got: 0
* Got: 0
* Got: 0
* ...
*/
class Queue {
int n;
synchronized int get() {
System.out.println("Got: " + n);
return n;
}
synchronized void put(int n) {
this.n = n;
System.out.println("Put: " + n);
}
}
class Consumer implements Runnable {
Queue q;
Consumer(Queue q) {
this.q = q;
new Thread(this, "Consumer").start();
}
public void run() {
while(true) {
q.get();
}
}
}
public class MainClass {
public static void main(String args[]) {
Queue q = new Queue();
new Consumer(q);
}
}
Related examples in the same category