专栏名称: java一日一条
主要是讲解编程语言java,并且每天都推送一条关于java编程语言的信息
目录
相关文章推荐
51好读  ›  专栏  ›  java一日一条

天天用Synchronized,底层原理是个啥?

java一日一条  · 公众号  · Java  · 2019-10-28 19:12

正文

请到「今天看啥」查看全文




对普通方法同步


代码段 2:


package com.paddx.test.concurrent;

public class SynchronizedTest {
public synchronized void method1(){
System.out.println("Method 1 start");
try {
System.out.println("Method 1 execute");
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Method 1 end");
}

public synchronized void method2(){
System.out.println("Method 2 start");
try {
System.out.println("Method 2 execute");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Method 2 end");
}

public static void main(String[] args) {
final SynchronizedTest test = new SynchronizedTest();

new Thread(new Runnable() {
@Override
public void run() {
test.method1();
}
}).start();

new Thread(new Runnable() {
@Override
public void run() {
test.method2();
}
}).start();
}
}



执行结果如下,跟代码段 1 比较,可以很明显的看出,线程 2 需要等待线程 1 的 Method1 执行完成才能开始执行 Method2 方法。


Method 1 start
Method 1 execute
Method 1 end
Method 2 start
Method 2 execute
Method 2 end



静态方法(类)同步


代码段 3:


package com.paddx.test.concurrent;

public class SynchronizedTest {
public static synchronized void method1(){
System.out.println("Method 1 start");
try {
System.out.println("Method 1 execute");
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Method 1 end");
}

public static synchronized void method2(){
System.out.println("Method 2 start");
try {
System.out.println("Method 2 execute");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Method 2 end");
}

public static void main(String[] args) {
final SynchronizedTest test = new SynchronizedTest();
final SynchronizedTest test2 = new SynchronizedTest();

new Thread(new Runnable() {
@Override
public void run() {
test.method1();
}
}).start();

new Thread(new Runnable() {
@Override
public void run() {
test2.method2();
}
}).start();
}
}







请到「今天看啥」查看全文