Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Counter {
- private int _val;
- public Counter(int n) {
- _val = n;
- }
- public void inc() {
- _val++;
- }
- public void dec() {
- _val--;
- }
- public int value() {
- return _val;
- }
- }
- class Mutex {
- public int whosTurn = 0;
- public boolean[] interested = {false, false};
- }
- class IThread extends Thread {
- private Counter cnt;
- private Mutex mutex;
- public IThread(Counter cnt, Mutex mutex) {
- this.cnt = cnt;
- this.mutex = mutex;
- }
- public void run() {
- for (int i = 0; i < 10000; i++) {
- mutex.interested[0] = true;
- mutex.whosTurn = 1;
- while (mutex.interested[1] && mutex.whosTurn == 1) {}
- cnt.inc();
- mutex.interested[0] = false;
- }
- }
- }
- class DThread extends Thread {
- private Counter cnt;
- private Mutex mutex;
- public DThread(Counter cnt, Mutex mutex) {
- this.cnt = cnt;
- this.mutex = mutex;
- }
- public void run() {
- for (int i = 0; i < 10000; i++) {
- mutex.interested[1] = true;
- mutex.whosTurn = 0;
- while (mutex.interested[0] && mutex.whosTurn == 0) {}
- cnt.dec();
- mutex.interested[1] = false;
- }
- }
- }
- public class Race {
- public static void main(String[] args) throws InterruptedException {
- Counter cnt = new Counter(0);
- Mutex mutex = new Mutex();
- Thread iThread = new IThread(cnt, mutex);
- Thread dThread = new DThread(cnt, mutex);
- iThread.start();
- dThread.start();
- iThread.join();
- dThread.join();
- System.out.println("stan=" + cnt.value());
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement