Skip to content

Instantly share code, notes, and snippets.

@rbe
Created October 22, 2010 07:02
Show Gist options
  • Select an option

  • Save rbe/640077 to your computer and use it in GitHub Desktop.

Select an option

Save rbe/640077 to your computer and use it in GitHub Desktop.
public class Consumer implements java.lang.Runnable {
private Queue queue;
private boolean stop;
public Consumer(Queue queue) {
this.queue = queue;
}
public synchronized void stopWork() { stop = true; }
@Override
public void run() {
while (!stop) {
System.out.println("Got: " + queue.remove());
}
}
}
public class CPTest {
public static void main(String[] args) {
// Create queue
Queue q = new Queue();
// Start producers
Producer p = new Producer(q);
for (int i = 0; i < 3; i++) {
new Thread(p).start();
}
// Start consumer
Consumer c = new Consumer(q);
new Thread(c).start();
// Wait some time
Thread.sleep(2 * 1000);
// ... and stop producing
p.stopWork();
// Wait some time
Thread.sleep(2 * 1000);
// ... and stop consuming
c.stopWork();
}
}
public class LockTest {
private Object rendezvous;
/**
* Locking using a synchronized block.
*/
public void doSomething() {
// Some code
// Critical section: try to get lock from instance 'rendezvous'
synchronized (rendezvous) {
// The code in this block is executed only once at a time; whoever gets the lock first
// This is used to protect modifications of a certain object; to make them atomic
// Modify data...
} // The lock is given back automatically when this block was left
// More code
}
/**
* You can also use the lock from 'this' by synchronizing on the method.
*/
public synchronized void anotherTask() {
// No other method call will be executed on this instance of LockTest until this method was left!
}
}
/**
* Do something in background.
*/
class MyRunnable implements java.lang.Runnable {
@Override
public void run() {
// Do something
}
}
public class MyThread {
public static void main(String[] args) {
// Start thread
new java.lang.Thread(new MyRunnable()).start()
}
}
public class Producer implements java.lang.Runnable {
private Queue queue;
private boolean stop;
public Producer(Queue queue) {
this.queue = queue;
}
public synchronized void stopWork() { stop = true; }
@Override
public void run() {
while (!stop) {
// Generate a number
Double d = Math.random();
System.out.println("Produced: " + d);
// ... and put it in the queue
queue.add(d);
}
}
}
public class Queue {
private List list;
public Queue() {
list = new ArrayList();
}
public synchronized void add(Double i) {
// Notify other waiting thread
// The call to notify() will take effect after the synchronized block was left!
this.notify();
list.add(i);
}
public synchronized Double remove() {
while (list.size() == 0) {
try {
this.wait();
} catch (InterruptedException e) {
// Ignore
}
}
list.remove(0);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment