Last active
September 11, 2015 10:44
-
-
Save glebmtb/1111af66451dfc1fb594 to your computer and use it in GitHub Desktop.
Hello World synchronized
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 TestNotify { | |
public static void main(String[] args) { | |
Stock stock = new Stock(); | |
Thread consumer = new Thread(new Consumer(stock)); | |
Thread producer = new Thread(new Producer(stock)); | |
consumer.start(); | |
producer.start(); | |
} | |
static class Producer implements Runnable { | |
final Stock stock; | |
public Producer(Stock stock) { | |
this.stock = stock; | |
} | |
@Override | |
public void run() { | |
for (Integer i = 1; i < 10; i++) { | |
synchronized (stock) { | |
whail(stock.isSetNew()){ | |
try { | |
stock.wait(); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
stock.set(i.toString()); | |
System.out.println(i + ". Producer set: " + i); | |
stock.notify(); | |
} | |
} | |
} | |
} | |
static class Consumer implements Runnable { | |
final Stock stock; | |
public Consumer(Stock stock) { | |
this.stock = stock; | |
} | |
@Override | |
public void run() { | |
for (int i = 1; i < 10; i++) { | |
synchronized (stock) { | |
whail(!stock.isSetNew()){ | |
try { | |
stock.wait(); | |
} catch (InterruptedException e) { | |
e.printStackTrace(); | |
} | |
} | |
System.out.println(i + ". Consumer get: " + stock.get()); | |
stock.notify(); | |
} | |
} | |
} | |
} | |
static class Stock { | |
private Deque<String> boxs = new LinkedList<String>(); | |
private boolean isSetNew = false; | |
void set(String box) { | |
isSetNew = true; | |
boxs.push(box); | |
} | |
String get() { | |
isSetNew = false; | |
return boxs.peek(); | |
} | |
boolean isSetNew() { | |
return isSetNew; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment