synchronized的底层是使用操作系统的mutex lock实现的。
当线程释放锁时,JMM会把该线程对应的工作内存中的共享变量刷新到主内存中
当线程获取锁时,JMM会把该线程对应的本地内存置为无效。从而使得被监视器保护的临界区代码必须从主内
存中读取共享变量
synchronized用的锁是存在java对象里头的。
synchronized同步快对同一条线程来说是可重入的,不会出现自己把自己锁死的问题;
同步块在已进入的线程执行完之前,会阻塞后面其他线程的进入。
实际举例如下:
1.锁对象(可能表述不够准确,求斧正)
public class SynchronizedDemo {
public synchronized void method() {
}
public static void main(String[] args) {
SynchronizedDemo demo = new SynchronizedDemo();
demo.method(); // 进入方法会锁 demo 指向对象中的锁;出方法会释放 demo 指向的对象中的锁
}
}
这里举一个3个黄牛抢票的例子
class MyThread implements Runnable {
private int ticket = 100 ; // 一共100张票
@Override
public synchronized void run() {
for (int i = 0; i < 100; i++) {
// 在同一时刻,只允许一个线程进入代码块处理
if(this.ticket>0) { // 还有票
try {
Thread.sleep(20);
} catch (InterruptedException e) {
}
System.out.println(Thread.currentThread().getName()+",还有" +
--this.ticket +" 张票");
}
}
}
}
public class TestDemo {
public static void main(String[] args) {
MyThread mt = new MyThread() ;
Thread t1 = new Thread(mt,"黄牛A");
Thread t2 = new Thread(mt,"黄牛B");
Thread t3 = new Thread(mt,"黄牛C");
t1.start();
t2.start();
t3.start();
}
}
在run()前加上synchronized 关键字后本来三个黄牛竞争的局面就会变成黄牛A垄断所有票情况
2.锁类的对象
public class SynchronizedDemo {
public synchronized static void method() {
}
public static void main(String[] args) {
method(); // 进入方法会锁 SynchronizedDemo.class 指向对象中的锁;出方法会释放
//SynchronizedDemo.class 指向的对象中的锁
}
}
继续举买票的例子
public class TestDemo {
static private int ticket = 100;
// 一共100张票
public synchronized static void go() {
for (int i = 0; i <= 100; i++) {
// 在同一时刻,只允许一个线程进入代码块处理
if(ticket > 0) { // 还有票
try {
Thread.sleep(20);
} catch (InterruptedException e) {
}
System.out.println(Thread.currentThread().getName()+",还有" +
--ticket +" 张票");
}
}
}
public static void main(String[] args) {
go();
}
}
3.锁具体的代码
public class SynchronizedDemo {
public void method() {
// 进入代码块会锁 this 指向对象中的锁;出代码块会释放 this 指向的对象中的锁
synchronized (this) {
}
}
public static void main(String[] args) {
SynchronizedDemo demo = new SynchronizedDemo();
demo.method();
}
}
这里就变成了三个黄牛竞争的局面
class MyThread implements Runnable {
private int ticket = 100 ; // 一共100张票
@Override
public void run() {
for (int i = 0; i < 100; i++) {
// 在同一时刻,只允许一个线程进入代码块处理
synchronized(this) { // 表示为程序逻辑上锁
if(this.ticket > 0) { // 还有票
try {
Thread.sleep(20);
} catch (InterruptedException e) {
}
System.out.println(Thread.currentThread().getName()+",还有" +
--this.ticket +" 张票");
}
}
}
}
}
public class TestDemo {
public static void main(String[] args) {
MyThread mt = new MyThread() ;
Thread t1 = new Thread(mt,"黄牛A");
Thread t2 = new Thread(mt,"黄牛B");
Thread t3 = new Thread(mt,"黄牛C");
t1.start();
t2.start();
t3.start();
}
}
希望可以对你有所帮助!