线程初步

来源:互联网 发布:淘宝房源 编辑:程序博客网 时间:2024/05/19 04:02

package com.test;

public class DeadLock {

String s1="我是S1";String s2="我是S2";int n = 1;public void write(){    synchronized (s1) {        try {            Thread.sleep(1000);        } catch (InterruptedException e) {            e.printStackTrace();        }        synchronized (s2) {            s1 = "修改s1----"+n+"次";            System.out.println(s1);        }    }    n++;}public void read(){    synchronized (s2) {        try {            Thread.sleep(1000);        } catch (InterruptedException e) {            e.printStackTrace();        }        synchronized (s1) {            s2 = "修改s2---"+n+"次";            System.out.println(s2);        }    }    n++;}

}
package com.test;

public class MyDeadLock implements Runnable{

private DeadLock dl;public MyDeadLock(DeadLock dl){    this.dl = dl;}@Overridepublic void run() {    for (int i = 0; i <10; i++) {        dl.read();        dl.write();    }}

}

package com.test;

public class TestDead {

public static void main(String[] args) {    DeadLock dd = new DeadLock();    MyDeadLock md = new MyDeadLock(dd);    new Thread(md).start();    new Thread(md).start();}

}

0 0
原创粉丝点击