java synchronized用法
一、使用的时候要注意
1.无论synchronized是加在方法还是对象上,它取得的锁都是对象的,而不是将一段代码或者方法锁定。
2.每个对象只有一个lock与之对应。
3.实现同步要比较大的系统开销。
二、synchronized关键字作用域有两种
1.在一个对象实例内,synchronized aMethod(){}可以防止多个线程同时访问这个对象的synchronized方法,如果一个对象有多个synchronized
方法,其它的线程不能同时访问这个对象中的任何一个synchronized方法。但是相同类的不同实例之间synchronized方法是不相干扰的。
2.在类的范围中,synchronized static aStaticMethod(){}防止多个线程同时访问这个类中的synchronized static 方法,它可以对类的所有实例起
作用。
例子:
电影院有20张票,三个seller同时在卖。
package javastudy;
public class Test7 {
public static void main(String [] args){
SellThread sellThread = new SellThread();
Thread sell1 = new Thread(sellThread,"sell1");
Thread sell2 = new Thread(sellThread, "sell2");
Thread sell3 = new Thread(sellThread, "sell3");
sell1.start() ;
sell2.start();
sell3.start() ;
}
}
class SellThread implements Runnable{
private int i=20;
public void run() {
while(true){
synchronized (this) {
if (i>0){
try {
Thread.sleep(1000);
} catch (Exception e) {
// TODO: handle exception
}
System.out.println(Thread.currentThread().getName()+":"+i--);
}
}
}
}
}
运行结果
sell2:20
sell2:19
sell2:18
sell3:17
sell1:16
sell1:15
sell3:14
sell3:13
sell3:12
sell3:11
sell2:10
sell3:9
sell1:8
sell3:7
sell3:6
sell3:5
sell3:4
sell3:3
sell3:2
sell3:1

浙公网安备 33010602011771号