package cn.com.io.threadDemo.ThreadSyn; 9. 10./** 11. * 通过两个属性值创建死锁 12. * 本程序通过两个线程各自锁定一个属性值,这样两个线程都无法结束,造成死锁 13. * @author Administrator 14. * 15. */ 16.public class ThreadSyn2 implements Runnable{ 17. 18. private static Object obj1=new Object(); 19. 20. private static Object obj2=new Object(); 21. 22. /** 23. * @param args 24. */ 25. public static void main(String[] args) { 26. ThreadSyn2 ts1=new ThreadSyn2(); 27. ThreadSyn2 ts2=new ThreadSyn2(); 28. 29. Thread t1=new Thread(ts1);//线程1 30. Thread t2=new Thread(ts2);//线程2 31. t1.setName("theOne"); 32. t2.setName("theTwo"); 33. 34. t1.start(); 35. t2.start(); 36. 37. } 38. 39. public void run() { 40. String name=Thread.currentThread().getName(); 41. if(name.equals("theOne")){ 42. method1(name); 43. }else{ 44. method2(name); 45. } 46. 47. } 48. 49. //线程1的方法锁定obj1,线程2就无法完成 50. private void method1(String name) { 51. System.out.println(name); 52. synchronized(obj1){ 53. try { 54. Thread.sleep(1000); 55. } catch (InterruptedException e) { 56. e.printStackTrace(); 57. } 58. synchronized(obj2){ 59. System.out.println(obj2); 60. } 61. } 62. } 63. 64. //线程1的方法锁定obj2,线程1就无法完成 65. private void method2(String name) { 66. System.out.println(name); 67. synchronized(obj2){ 68. try { 69. Thread.sleep(1000); 70. } catch (InterruptedException e) { 71. e.printStackTrace(); 72. } 73. synchronized(obj1){ 74. System.out.println(obj1); 75. } 76. } 77. } 78.}