Created
March 26, 2015 13:12
-
-
Save Biazus/886c87c16da26b5a9d64 to your computer and use it in GitHub Desktop.
Monitores em Java
This file contains 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.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