您的位置:首页 > 其它

线程初步

2015-09-07 15:25 190 查看
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;
}

@Override
public 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();
}


}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: