Created
September 3, 2014 07:43
-
-
Save gnosis23/8de054c9b3f12db57bdd to your computer and use it in GitHub Desktop.
safe publication
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
| 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