 |
建站必读 |
 |
|
|
 |
|
 |
|
| |
| 当前位置:首页 -> 建站必读 -> JSP技术 |
|
转自别的论坛的一篇关于synchronized的讨论 |
关于 synchronized 的使用???
jaja
--------------------------------------------------------------------------------
synchronized 是对某一方法或对象加锁, 只有拥有锁才能访问执行方法或其括号中的代码, OK, 这个道理我明白, 但是好象实际却不是这回事.
public class SyncTest{
public static void main(String[] args){
final StringBuffer s1=new StringBuffer();
final StringBuffer s2=new StringBuffer();
new Thread() {
public void run(){ //只有拥有s1的锁,才可以执行后面的代码,
synchronized(s1){ //现在当前线程有S1的锁
s1.append("A");
synchronized(s2){ // 当前线程有S2的锁吗, 我不知道?? 好象有吧
s2.append("B");
System.out.print(s1);
System.out.print(s2);
}
}
}
}.start(); // 如果有S2的锁, 打印出AB
new Thread(){
public void run(){
synchronized(s2){ //当前线程有S2的锁吗??? 我一点也不知道
s2.append("C");
synchronized(s1){
s1.append("D");
System.out.println(s2);
System.out.println(s1);
}
}
}
}.start();
}
}
哪位兄台可以详解一下? MM先行谢过
小乌
--------------------------------------------------------------------------------
the lock of the objects will be released after the synchronized code
public class SyncTest{
public static void main(String[] args){
final StringBuffer s1=new StringBuffer();
final StringBuffer s2=new StringBuffer();
new Thread() {
public void run(){ //
synchronized(s1){ // 现在当前线程有S1的锁
s1.append("A");
synchronized(s2){ // 当前线程拥有有S2的锁
s2.append("B");
System.out.print(s1);
System.out.print(s2);
} // 释放S2的锁
} // 释放S1的锁
}
}.start(); // 如果有S2的锁, 打印出AB
new Thread(){
public void run(){
synchronized(s2){ // 当前线程有S2的锁
s2.append("C");
synchronized(s1){ // 现在当前线程有S1的锁
s1.append("D");
System.out.println(s2);
System.out.println(s1);
} // 释放S1的锁
} // 释放S2的锁
}
}.start();
}
}
chairyuan
--------------------------------------------------------------------------------
GG我来也:
这个程序之所以显得正确,是因为每个thread都非常之快地运行结束。
public class SyncTest{
public static void main(String[] args){
final StringBuffer s1=new StringBuffer();
final StringBuffer s2=new StringBuffer();
new Thread() {
public void run(){ //只有拥有s1的锁,才可以执行后面的代码,
synchronized(s1){ //现在当前线程有S1的锁
s1.append("A");
synchronized(s2){ // 当前线程有S2的锁
&nbs |
| |
|
| |
本站关键词: |
|
|
|
|
 |
|
 |
|