Compare commits
No commits in common. 'dev' and 'master' have entirely different histories.
1 changed files with 0 additions and 65 deletions
@ -1,70 +1,5 @@
|
||||
package org.chulk.sanxbox; |
||||
|
||||
import org.junit.jupiter.api.Test; |
||||
|
||||
public class TestConcurrency { |
||||
|
||||
private int counter = 0; |
||||
private final Object lock1 = new Object(); |
||||
private final Object lock2 = new Object(); |
||||
|
||||
@Test |
||||
public void testDeadlock() throws InterruptedException { |
||||
Runnable incRun = () -> { |
||||
try { |
||||
for (int i = 0; i < 100; i++) { |
||||
incrementCounter(); |
||||
System.out.println("Incrementing " + i); |
||||
} |
||||
} catch (InterruptedException ie) { |
||||
} |
||||
}; |
||||
|
||||
Runnable decRun = () -> { |
||||
try { |
||||
for (int i = 0; i < 100; i++) { |
||||
decrementCounter(); |
||||
System.out.println("Decrementing " + i); |
||||
} |
||||
} catch (InterruptedException ie) { |
||||
} |
||||
}; |
||||
|
||||
Thread thread1 = new Thread(incRun); |
||||
Thread thread2 = new Thread(decRun); |
||||
|
||||
thread1.start(); |
||||
// sleep to make sure thread 1 gets a chance to acquire lock1
|
||||
Thread.sleep(100); |
||||
thread2.start(); |
||||
|
||||
thread1.join(); |
||||
thread2.join(); |
||||
|
||||
System.out.println("Done : " + counter); |
||||
|
||||
} |
||||
|
||||
void incrementCounter() throws InterruptedException { |
||||
synchronized (lock1) { |
||||
System.out.println("Acquired lock1"); |
||||
Thread.sleep(100); |
||||
|
||||
synchronized (lock2) { |
||||
counter++; |
||||
} |
||||
} |
||||
} |
||||
|
||||
void decrementCounter() throws InterruptedException { |
||||
synchronized (lock2) { |
||||
System.out.println("Acquired lock2"); |
||||
|
||||
Thread.sleep(100); |
||||
synchronized (lock1) { |
||||
counter--; |
||||
} |
||||
} |
||||
} |
||||
|
||||
} |
||||
|
Loading…
Reference in new issue