Skip to content

Instantly share code, notes, and snippets.

@Biazus
Created March 26, 2015 13:12
Show Gist options
  • Save Biazus/886c87c16da26b5a9d64 to your computer and use it in GitHub Desktop.
Save Biazus/886c87c16da26b5a9d64 to your computer and use it in GitHub Desktop.
Monitores em Java
import java.util.Random;
class MyMonitor {
private int data = 0;
private int turn = 1;
public synchronized void update(int id) throws InterruptedException {
while(turn != id)
wait();
System.out.println("Thread ID = " + id + " vai atualizar ...");
data++; Thread.currentThread().sleep(new Random().nextInt(3000));
System.out.println("Thread ID = " + id + " atualizou...");
turn = (turn + 1) % 2;
notify();
}
}
class MyThread extends Thread {
int id;
MyMonitor myMonitor;
public MyThread(int id, MyMonitor myMonitor) {
this.id = id;
this.myMonitor = myMonitor;
}
public void run() {
while (true) {
try {
myMonitor.update(id);
Thread.currentThread().sleep(new Random().nextInt(3000));
}
catch (InterruptedException ie) {
ie.printStackTrace();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment