/**
* Created by Leon on 2017/5/23.
* Java多线程
* 对于synchronized的理解
*/
public class TT implements Runnable
{
int b=100;
public synchronized void m1() throws Exception
//锁定只锁定这段代码,另外一个线程不能执行这个方法,但是可以执行其他方法
{
b=1000;
Thread.sleep(5000);
System.out.println("M1: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
{
TT tt=new TT();
Thread t=new Thread(tt);
t.start();
Thread.sleep(1000);
tt.m2();
}
}
输出为:
1000
M1:b=1000
修改m2方法和main方法
public synchronized void m2() throws Exception
{
Thread.sleep(2500);
b=2000;
}
public static void main(String[] args) throws Exception
{
TT tt=new TT();
Thread t=new Thread(tt);
t.start();
Thread.sleep(1000);
tt.m2();
System.out.println(tt.b);
}
输出变为:
M1:b=1000
2000
总结:
一、当两个并发线程访问同一个对象object中的这个synchronized(this)同步代码块时,一个时间内只能有一个线程得到执行。另一个线程必须等待当前线程执行完这个代码块以后才能执行该代码块。
二、然而,当一个线程访问object的一个synchronized(this)同步代码块时,另一个线程仍然可以访问该object中的非synchronized(this)同步代码块。
三、尤其关键的是,当一个线程访问object的一个synchronized(this)同步代码块时,它就获得了这个object的对象锁。结果,其他线程对object中所有其它synchronized(this)同步代码块的访问将被阻塞。
四、读的功能不用加锁,改的功能要加锁。允许多个进程一起读,不能一起改。