一、基本概念
synchronized英文意思是同步的,该关键字代表这个方法加锁,不管哪一个线程(如线程A),运行到这个方法时,都要检查有没有其它线程B(或者C、D等)正在用这个方法。若有则要等正在使用synchronized方法的线程B(或者C、D)运行完这个方法后再运行此线程A。若没有则直接运行。有两种用法可以实现:synchronized 方法和synchronized 块。
二、代码示例
代码摘自张孝祥老师的线程视频源码,演示了synchronized块、synchronized方法和静态synchronized方法。
public class TraditionalThreadSynchronized
{
public static void main(String[] args)
{
new TraditionalThreadSynchronized().init();
}
private void init()
{
final Outputer outputer = new Outputer();
// 线程1
new Thread(new Runnable()
{
public void run()
{
while (true)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
outputer.output1("zhangxiaoxiang");
}
}
}).start();
// 线程2
new Thread(new Runnable()
{
public void run()
{
while (true)
{
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
Outputer.output3("lihuoming");
}
}
}).start();
}
// 若不测试output3静态方法,该类就无必要加static。不加static也不影响利用Outputer.class这个锁
static class Outputer
{
// 和output3用的同一把锁,这个锁是该类在内存中的字节码
public void output1(String name)
{
int len = name.length();
synchronized (Outputer.class)
{
for (int i = 0; i < len; i++)
{
System.out.print(name.charAt(i));
}
System.out.println();
}
}
// 普通方法加synchronized,这个锁是该类的对象:synchronized(this)
// output2和output1,output3用的不是同一把锁,故无法同步
// 将output1中改为synchronized(this)即可和output2同步
public synchronized void output2(String name)
{
int len = name.length();
for (int i = 0; i < len; i++)
{
System.out.print(name.charAt(i));
}
System.out.println();
}
// 静态方法加synchronized,这个锁是该类在内存中的字节码:synchronized (Outputer.class)
public static synchronized void output3(String name)
{
int len = name.length();
for (int i = 0; i < len; i++)
{
System.out.print(name.charAt(i));
}
System.out.println();
}
}
}
原帖地址:http://baike.baidu.com/link?url=YWtyx22uUVGwn2275G7U9DSbPBfXhNe-MQ-jic6--OlWYMsUNFyJgPrneJ9DJ8umj_Eme1hL1sBHLpV6XIMEFK#3