- 03.package com.ljl.thread;
- 04.public class DealLock implements Runnable {
- 05. private int flag = 1;
- 06. // 此对象必须是静态的,同步必须是被多个线程共享
- 07. static Object resource1 = new Object(), resource2 = new Object();
- 08.
- 09. public void run() {
- 10. if (flag == 1) {
- 11. synchronized (resource1) {
- 12. System.out.println("resource1");
- 13. try {
- 14. Thread.sleep(1000);
- 15. } catch (InterruptedException e) {
- 16. // TODO Auto-generated catch block
- 17. e.printStackTrace();
- 18. }
- 19. synchronized (resource2) {
- 20. System.out.println("resource2");
- 21. }
- 22. }
- 23. }
- 24. if (flag == 0) {
- 25. synchronized (resource2) {
- 26. System.out.println("resource2");
- 27. try {
- 28. Thread.sleep(1000);
- 29. } catch (InterruptedException e) {
- 30. // TODO Auto-generated catch block
- 31. e.printStackTrace();
- 32. }
- 33. synchronized (resource1) {
- 34. System.out.println("resource1");
- 35. }
- 36. }
- 37. }
- 38. }
- 39.
- 40. public static void main(String[] args) {
- 41. DealLock lock1 = new DealLock();
- 42. DealLock lock2 = new DealLock();
- 43. lock1.flag = 1;
- 44. lock2.flag = 0;
- 45. Thread ll1 = new Thread(lock1);
- 46. Thread ll2 = new Thread(lock2);
- 47. ll1.start();
- 48. ll2.start();
- 49. }
- 50.}
复制代码 |