TestSynchronized.java 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import java.util.concurrent.*;
  2. public class TestSynchronized {
  3. public static void main(String[] args) throws Exception {
  4. ExecutorService executor = Executors.newCachedThreadPool();
  5. SyncSample ss = new SyncSample();
  6. executor.execute(() -> ss.func1());
  7. executor.execute(() -> ss.func1());
  8. Thread.sleep(100);
  9. executor.execute(() -> ss.func2());
  10. executor.execute(() -> ss.func2());
  11. Thread.sleep(100);
  12. SyncSample ss2 = new SyncSample();
  13. executor.execute(() -> ss.func3());
  14. executor.execute(() -> ss2.func3());
  15. executor.shutdown();
  16. }
  17. }
  18. class SyncSample {
  19. public void func1() {
  20. System.out.println("Before sync this");
  21. try {
  22. Thread.sleep(10);
  23. } catch (Exception e) {
  24. e.printStackTrace();
  25. }
  26. synchronized (this) {
  27. for (int i = 0; i < 5; i++)
  28. System.out.println(i);
  29. }
  30. }
  31. public synchronized void func2() {
  32. System.out.println("Before sync method");
  33. try {
  34. Thread.sleep(10);
  35. } catch (Exception e) {
  36. e.printStackTrace();
  37. }
  38. for (int i = 0; i < 5; i++)
  39. System.out.println(i);
  40. }
  41. public void func3() {
  42. System.out.println("Before sync class");
  43. try {
  44. Thread.sleep(10);
  45. } catch (Exception e) {
  46. e.printStackTrace();
  47. }
  48. synchronized (SyncSample.class) {
  49. for (int i = 0; i < 5; i++)
  50. System.out.println(i);
  51. }
  52. }
  53. }