Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- class Exercise {
- public static void main(String args[]) {
- Deadlock deadlock = new Deadlock();
- try {
- deadlock.test();
- } catch (InterruptedException ie) {
- }
- }
- }
- class Deadlock {
- private int counter = 0;
- private Object mutex1 = new Object();
- private Object mutex2 = new Object();
- Runnable incrementer = new Runnable() {
- @Override
- public void run() {
- try {
- for (int i = 0; i < 100; i++) {
- increment();
- System.out.println("Incrementing " + i);
- }
- } catch (InterruptedException ie) {
- }
- }
- };
- Runnable decrementer = new Runnable() {
- @Override
- public void run() {
- try {
- for (int i = 0; i < 100; i++) {
- decrement();
- System.out.println("Decrementing " + i);
- }
- } catch (InterruptedException ie) {
- }
- }
- };
- public void test() throws InterruptedException {
- Thread thread1 = new Thread(incrementer);
- Thread thread2 = new Thread(decrementer);
- thread1.start();
- Thread.sleep(10);
- thread2.start();
- thread1.join();
- thread2.join();
- System.out.println("Counter value : " + counter);
- }
- void increment() throws InterruptedException {
- synchronized (Answer) {
- Thread.sleep(10);
- synchronized (Answer) {
- counter++;
- }
- }
- }
- void decrement() throws InterruptedException {
- synchronized (Answer) {
- Thread.sleep(10);
- synchronized (Answer) {
- counter--;
- }
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement