Showing the changes to java/tests/ThreadTest.java (1 of 11 files). Show all
Unified · Split
| @@ -0,0 +1,61 @@ | ||
| 1 | + | |
| 2 | +import static utils.Utils.*; | |
| 3 | + | |
| 4 | +public class ThreadTest { | |
| 5 | + | |
| 6 | + private static class Integer { | |
| 7 | + private int data; | |
| 8 | + | |
| 9 | + Integer(int data) { | |
| 10 | + this.data = data; | |
| 11 | + } | |
| 12 | + | |
| 13 | + int getData() { | |
| 14 | + return data; | |
| 15 | + } | |
| 16 | + | |
| 17 | + void setData(int data) { | |
| 18 | + this.data = data; | |
| 19 | + } | |
| 20 | + | |
| 21 | + } | |
| 22 | + | |
| 23 | + public static void main(String[] args) throws InterruptedException { | |
| 24 | + final Integer var = new Integer(0); | |
| 25 | + Thread testThread = new Thread(new Runnable() { | |
| 26 | + @Override | |
| 27 | + public void run() { | |
| 28 | + var.setData(42); | |
| 29 | + } | |
| 30 | + }); | |
| 31 | + testThread.start(); | |
| 32 | + testThread.join(); | |
| 33 | + assertEquals(42, var.getData()); | |
| 34 | + | |
| 35 | + Thread testThread1 = new Thread(new Runnable() { | |
| 36 | + @Override | |
| 37 | + public void run() { | |
| 38 | + for (int i = 0; i < 2000; i++) { | |
| 39 | + synchronized (var) { | |
| 40 | + var.setData(var.getData() + 1); | |
| 41 | + } | |
| 42 | + } | |
| 43 | + } | |
| 44 | + }); | |
| 45 | + Thread testThread2 = new Thread(new Runnable() { | |
| 46 | + @Override | |
| 47 | + public void run() { | |
| 48 | + for (int i = 0; i < 1000; i++) { | |
| 49 | + synchronized (var) { | |
| 50 | + var.setData(var.getData() - 1); | |
| 51 | + } | |
| 52 | + } | |
| 53 | + } | |
| 54 | + }); | |
| 55 | + testThread1.start(); | |
| 56 | + testThread2.start(); | |
| 57 | + testThread1.join(); | |
| 58 | + testThread2.join(); | |
| 59 | + assertEquals(1042, var.getData()); | |
| 60 | + } | |
| 61 | +} | |