1. public class Test {
    2. public static int A = 0;
    3. public static Object object = new Object();
    4. public static void main(String[] args) throws InterruptedException {
    5. Thread thread1 = new Thread(new RunnableA());
    6. Thread thread2 = new Thread(new RunnableA());
    7. Thread thread3 = new Thread(new RunnableB());
    8. Thread thread4 = new Thread(new RunnableB());
    9. thread1.start();
    10. thread2.start();
    11. thread3.start();
    12. thread4.start();
    13. }
    14. }
    15. class RunnableA implements Runnable {
    16. @Override
    17. public void run() {
    18. synchronized (Test.object) {
    19. Test.A++;
    20. }
    21. }
    22. }
    23. class RunnableB implements Runnable {
    24. @Override
    25. public void run() {
    26. synchronized (Test.object) {
    27. Test.A--;
    28. }
    29. }
    30. }
    1. public class Test {
    2. public static void main(String[] args) throws InterruptedException {
    3. Data data = new Data();
    4. Thread thread1 = new Thread(new RunnableA(data));
    5. Thread thread2 = new Thread(new RunnableA(data));
    6. Thread thread3 = new Thread(new RunnableB(data));
    7. Thread thread4 = new Thread(new RunnableB(data));
    8. thread1.start();
    9. thread2.start();
    10. thread3.start();
    11. thread4.start();
    12. }
    13. }
    14. class Data {
    15. private int A = 0;
    16. public synchronized void increase() {
    17. A++;
    18. }
    19. public synchronized void decrease() {
    20. A--;
    21. }
    22. public int getA() {
    23. return A;
    24. }
    25. }
    26. class RunnableA implements Runnable {
    27. private Data data;
    28. public RunnableA(Data data) {
    29. this.data = data;
    30. }
    31. @Override
    32. public void run() {
    33. data.increase();
    34. }
    35. }
    36. class RunnableB implements Runnable {
    37. private Data data;
    38. public RunnableB(Data data) {
    39. this.data = data;
    40. }
    41. @Override
    42. public void run() {
    43. data.decrease();
    44. }
    45. }