Skip to content

Instantly share code, notes, and snippets.

@glebmtb
Last active September 11, 2015 10:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save glebmtb/1111af66451dfc1fb594 to your computer and use it in GitHub Desktop.
Save glebmtb/1111af66451dfc1fb594 to your computer and use it in GitHub Desktop.
Hello World synchronized
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