- /**
- * 通过两个属性值创建死锁
- * 本程序通过两个线程各自锁定一个属性值,这样两个线程都无法结束,造成死锁
- * @author Administrator
- *
- */
- public class ThreadSyn2 implements Runnable{
-
- private static Object obj1=new Object();
-
- private static Object obj2=new Object();
- /**
- * @param args
- */
- public static void main(String[] args) {
- ThreadSyn2 ts1=new ThreadSyn2();
- ThreadSyn2 ts2=new ThreadSyn2();
-
- Thread t1=new Thread(ts1);//线程1
- Thread t2=new Thread(ts2);//线程2
- t1.setName("theOne");
- t2.setName("theTwo");
-
- t1.start();
- t2.start();
- }
- public void run() {
- String name=Thread.currentThread().getName();
- if(name.equals("theOne")){
- method1(name);
- }else{
- method2(name);
- }
-
- }
- //线程1的方法锁定obj1,线程2就无法完成
- private void method1(String name) {
- System.out.println(name);
- synchronized(obj1){
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- synchronized(obj2){
- System.out.println(obj2);
- }
- }
- }
- //线程1的方法锁定obj2,线程1就无法完成
- private void method2(String name) {
- System.out.println(name);
- synchronized(obj2){
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- synchronized(obj1){
- System.out.println(obj1);
- }
- }
- }
- }
复制代码 http://z13574401906.blog.163.com/blog/static/11206731820102841125368/
|