Skip to content

Instantly share code, notes, and snippets.

@gnosis23
Created September 3, 2014 07:43
Show Gist options
  • Select an option

  • Save gnosis23/8de054c9b3f12db57bdd to your computer and use it in GitHub Desktop.

Select an option

Save gnosis23/8de054c9b3f12db57bdd to your computer and use it in GitHub Desktop.
safe publication
package chap06;
import java.util.concurrent.TimeUnit;
/**
* Created by wang.bh
*/
class Bag {
private final String item; // <-- no final here
public String getItem() {
return item;
}
public Bag(String item) {
this.item = item;
}
}
class ThreadB extends Thread {
private Bag bag;
public /*synchronized*/ void grab(Bag bag) {
this.bag = bag;
}
@Override
public void run() {
try {
while (true) {
//synchronized (this) {
if (bag != null) {
TimeUnit.MILLISECONDS.sleep(500);
System.out.println(bag.getItem());
}
//}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
public class SafePub {
public static void main(String args[]) throws InterruptedException {
ThreadB t = new ThreadB();
t.start();
TimeUnit.SECONDS.sleep(1);
Bag bag = new Bag("HI");
t.grab(bag);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment