互斥锁
1.Java在Java语言中,引入了对象互斥锁的概念,来保证共享数据操作的完整性
2.每个对象都对应于一个可称为"互斥锁"的标记,这个标记用来保证在任一时刻,只有能有一个线程来访问对象
3.关键字synchronized来与对象的互斥锁联系,当某个对象用synchronized修饰时,表明该对象在任一时刻只能由一个线程访问
4.同步的局限性,导致程序的执行效率降低‘
5.同步方法(非静态的)的锁可以是this,也可以是其他对象(要求是同一个对象)
6.同步方法(静态的)的所为当前类本身
public class ticket {
public static void main(String[] args) {
A a1 = new A();
A a2 = new A();
A a3 = new A();
a1.start();
a2.start();
a3.start();
}
}
class A extends Thread{
private static int left = 100;
boolean loop= true;
//同步方法(静态的)的所为当前类本身
//1.public synchronized static void m1(){}锁是加在A.class本身
public synchronized static void m1(){
}
//2.如果在静态方法中,实现一个同步代码块,不能用this 需使用 类.class
public static void m2(){
synchronized(A.class){
System.out.println("m2");
}
}
//1.public synchronized void m(){}就是一个同步方法
//2.这时锁在this对现象
public synchronized void m(){//同步方法
if(left <= 0){
System.out.println("售票结束...");
loop = false;
return;
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("窗口"+ Thread.currentThread().getName() +" 剩余 " + left-- + "张票" );
}
//3.也可以在代码块加锁,同步代码块
public /*synchronized*/ void m(){
synchronized (this) {
if (left <= 0) {
System.out.println("售票结束...");
loop = false;
return;
}
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("窗口" + Thread.currentThread().getName() + " 剩余 " + --left + "张票");
}
}
@Override
public void run() {
while(loop){
m();
}
}
}