synchronized关键字
在java编程中,经常需要用到同步,而用得最多的也许是synchronized关键字了。
在编写一个类时,如果该类中的代码可能运行在多线程环境下,会同时被多个线程访问的资源,就是竞争资源,也称为竞争条件。对于多线程共享的资源我们必须进行同步,以避免一个线程的改动被另一个线程所覆盖。
需要注意的是synchronized关键字锁的是对象,而不是代码,请看下面两个例子。
例子一,请分析代码输出:
/**
* 对某个对象加锁
* 分析一下这个程序的输出
* @author Forever
*
*/
public class Java_dxc005 implements Runnable{
private int count = 10;
public /*synchronized*/ void run() {
count--;
System.out.println(Thread.currentThread().getName() + " count = "+count);
}
public static void main(String[] args) {
Java_dxc005 t=new Java_dxc005();
for(int i=0; i<5; i++) {
new Thread(t, "Thread"+ i).start();
}
}
}
输出:
Thread0 count = 8
Thread3 count = 7
Thread1 count = 8
Thread4 count = 5
Thread2 count = 6
接下来我们再看代码二,再分析其输出:
/**
* 对某个对象加锁
* 分析一下这个程序的输出
* @author Forever
*
*/
public class Java_dxc006 implements Runnable{
private int count = 10;
public synchronized void run() {
count--;
System.out.println(Thread.currentThread().getName() + "count = "+count);
}
public static void main(String[] args) {
for(int i=0; i<5; i++)
{
Java_dxc006 t=new Java_dxc006();
new Thread(t,"Thread" + i).start();
}
}
}
输出:
Thread0count = 9
Thread4count = 9
Thread3count = 9
Thread1count = 9
Thread2count = 9
总结:
发现synchronized关键字关键字锁的是对象,例子一是锁同一个对象,例子二建立了五个对象,相当于每个synchronized关键字分别锁了一个对象。