1,synchronized : static method,Main.class是同步类锁的。
2,Main.staticLock是这个变量的索,不是类锁,可以同步获取。
3,synchronized : method,和类索不相关,可以2个Thread同时获取类锁和对象索和类的某个静态变量锁。
4,SomeObject.wait(),SomeObject.notifyAll()必须在一个锁下同步。
/*
* Main.java
*
* Created on 2005年6月30日, 上午11:08
*
* To change this template, choose Tools | Options and locate the template under
* the Source Creation and Management node. Right-click the template and choose
* Open. You can then make changes to the template in the Source Editor.
*/
package exceptionhandle;
/**
*
* @author Larry
*/
public class Main {
public static void main(String[] args) {
Main main=new Main();
main.t2.start();
main.t1.start();
}
//attributes
private static Object staticLock=new Object();
private Object lock=new Object();
//initialize threads
Thread t1=new Thread(new Runnable(){
public void run(){
methodTwo();
}
}
);
Thread t2=new Thread(new Runnable(){
public void run(){
methodThree();
}
}
);
/** Creates a new instance of Main */
public Main() {
}
public synchronized static void staticMethod(){
print("sync,static method start");
try{
Thread.sleep(6000);
}catch(InterruptedException e){}
print("sync,static method stop");
}
public synchronized void methodOne(){
print("sync,non-static methodOne start");
staticMethod();
try{
Thread.sleep(6000);
}catch(InterruptedException e){}
print("sync,non-static methodOne stop");
}
public synchronized void methodTwo(){
print("sync,non-static methodOne start");
try{
Thread.sleep(6000);
}catch(InterruptedException e){}
print("sync,non-static methodOne stop");
}
public void methodThree(){
print("enter methodThree");
synchronized(Main.class){
print("enter sync Main.class");
try{
Thread.sleep(6000);
}catch(InterruptedException e){}
print("exit sync Main.class");
}
}
public static void print(String str){
System.out.println(Thread.currentThread().getName()+":::"+str);
}
}
Trackback: http://tb.donews.net/TrackBack.aspx?PostId=453430