您的位置:首页 > 其它

synchronized 静态 非静态 方法 使用不同锁对象

2012-10-17 19:49 316 查看
http://developer.51cto.com/art/200906/132360.htm看此文章锁的一些实验验证

用synchronized分别修饰静态方法和非静态方法,使用的锁分别为

静态:class对象的锁

非静态:本对象的锁

实验1:对静态方法和非静态方法用synchronized进行修饰

结论:出现错乱的输出,说明静态方法和非静态方法用不同的锁

实验2:对静态方法用synchronized,非静态方法用synchronized块对 class对象加

结论:正确输出,确认静态方法确实使用class对象的锁,而非静态方法使用synchronized默认使用this锁(自己试试吧)

实验代码如下:

import java.io.*;

public class TestClassInstance{
public static void main(String[] args)throws IOException{
MyThread t1 = new MyThread();
YourThread t2 = new YourThread(t1);
t1.start();
t2.start();
}
}

class MyThread extends Thread
{
private static FileOutputStream out;
static{
try{
out = new FileOutputStream("1.txt");
}catch(IOException e){
}
}
public void run(){
try{
printlog();
}catch(IOException e){
}
}

public synchronized static void printlog()throws IOException{
OutputStreamWriter ou = new OutputStreamWriter(out);
//synchronized(MyThread.class){
for (int i = 0 ; i < 100000 ; i++ )
{
ou.write("*");
}
ou.flush();
//}
}

public synchronized void printmsg()throws IOException{
OutputStreamWriter ou = new OutputStreamWriter(out);
//synchronized(YourThread.class){
for (int i = 0 ; i < 100000; i++ )
{

ou.write("@");

//synchronized(YourThread.class){
//}
}
ou.flush();
//}
}
}
class YourThread extends Thread
{
private MyThread myThread;
public YourThread(MyThread m){
this.myThread = m;
}

public void run(){
try{
myThread.printmsg();
}catch(IOException e){
}
}
}


以上存自我学习,有什么错误请大家指教,大榭啊
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐