synchronized
Java中提供synchronized关键字实现同步处理,用synchoronized可以修饰代码块,修饰方法,来完成对 对象加锁,对类加锁的操作。synchoronized是重量级锁。意思就是当有一个线程A进入时其他想访问的线程阻塞师等待,等待该线程A执行完整个加锁区间,系统自动释放锁,并唤醒等待的其他线程竞争锁。
对象锁
synchronized修饰同步代码块 --锁new出来的实例化对象
synchoronized(this){}
代码举例子:
import sun.security.krb5.internal.Ticket;
class MyRunnable implements Runnable{
private Integer ticket = 100;
@Override
public void run(){
for(int i=0;i<100;i++){
synchronized (this){
if(ticket>0){
System.out.println(Thread.currentThread().getName()+"还剩"+(ticket--)+"张票");
}
}
}
}
}
public class Test{
public static void main(String[] args) {
Runnable runnable = new MyRunnable();
new Thread(runnable).start();
new Thread(runnable).start();
new Thread(runnable).start();
}
}
</