1.当变量被加上synchronized锁,同一时间只允许一个线程在synchronized内的代码块
2.被synchronized修饰的方法,相当于给方法上锁,同一时间只允许一个线程调用该方法
对于非静态方法,synchronized上锁的实际上是 this变量
对于静态方法,synchronized上锁的实际上是 Class变量 比方Demo类,上锁的是Demo.class(表示Class变量)
package test;
//4个窗口售票,每个窗口一个线程
class Ticket implements Runnable {
private static int tick = 100;
Object mutex = new Object();
public void run() {
while (true) {
//1.*****当变量(Object对象)被加上synchronized锁,只允许一个线程允许在synchronized内的代码块,如mutex
synchronized (mutex) {
if (tick > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) { // 复写Runnable的run方法,不提供异常抛出
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ ".....Sale : " + tick--);
}
}
}
}
public synchronized void show() { //2.*****非静态成员方法,锁this变量
if(tick > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) { // 复写Runnable的run方法,不提供异常抛出
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ ".....Sale : " + tick--);
}
}
public static synchronized void staticShow() { //3.*****静态成员方法,锁Class变量,这里是锁Ticket.class
if(tick > 0) {
try {
Thread.sleep(10);
} catch (InterruptedException e) { // 复写Runnable的run方法,不提供异常抛出
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ ".....Sale : " + tick--);
}
}
}
public class TicketDemo {
public static void main(String[] args) {
Ticket t = new Ticket();
Thread t1 = new Thread(t); //t为Runnable的实现
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
Thread t4 = new Thread(t);
t1.start();
t2.start();
t3.start();
t4.start();
}
}