1、synchronized的定义
2、synchronized的性能
3、示例
1.
public class TestSygn implements Runnable{
Timer timer=new Timer();
public static void main(String [] args){
TestSygn test=new TestSygn();
Thread t1=new Thread(test);
Thread t2=new Thread(test);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
public void run(){
timer.add(Thread.currentThread().getName());
}
}
class Timer{
private static int num=0;
public void add(String name){
synchronized (this) {
num++;
try{
Thread.sleep(1);
}catch(InterruptedException e){
}
System.out.println(name+",你是第"+num+"个使用timer的线程");
}
}
}
//锁住当前对象
//同时用一对象时,不可能有另一个线程再次进入这个对象实例的这个synchronized段执行
//但要注意,如果该对象如果还有其他方法,那么完全可以执行其他没有锁定的方法
//如果执行语句为:
class Timer{
private static int num=0;
public synchronized void add(String name){
//表示在执行方法时锁对当前对象的这个代码段
//synchroized (this) {
num++;
try{
Thread.sleep(1);
}catch(InterruptedException e){
}
System.out.println(name+",你是第"+num+"个使用timer的线程");
}
//}
}
2.
public class TestSync2 implements Runnable{
int b=100;
public synchronized void m1() throws Exception{
b=1000;
System.out.println("在前面的可以这样子的");
Thread.sleep(2000);
System.out.println("b = "+b);
}
public void m2(){
System.out.println(b);
}
public void run(){
try{
m1();
}catch(Exception e){
e.printStackTrace();
}
}
public static void main(String [] args) throws Exception{
TestSync2 t1=new TestSync2();
Thread tt1=new Thread(t1);
tt1.start();
Thread.sleep(1000);
t1.m2();//证明是锁定了当前对象的某个方法,
} //而其他方法还是可以继续被访问的.
}
//输出的是执行m2方法的时候输入出的是1000