1. 两个普通的synchronized
package ThreadTest;
import java.util.concurrent.TimeUnit;
public class ThreadTest02 {
public static void main(String[] args) {
Phone phone = new Phone();
new Thread(phone::sendMsg, "A").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(phone::call, "B").start();
}
}
class Phone{
public synchronized void sendMsg(){
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Send message!");
}
public synchronized void call(){
System.out.println("Call");
}
}
这段代码的执行顺序是:
线程A获得phone的锁等待4s,同时main等待1s,因为1s小于4s,所以4s过后线程A打印发信息的函数,瞬间释放锁,线程B拿到锁执行call
2. 两个带有static的同步方法
package ThreadTest;
import java.util.concurrent.TimeUnit;
public class ThreadTest02 {
public static void main(String[] args) {
Phone phone1 = new Phone();
Phone phone2 = new Phone();
new Thread(()->{
phone1.sendMsg();
}, "A").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
phone2.call();
}, "B").start();
}
}
class Phone{
public static synchronized void sendMsg(){
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Send message!");
}
public static synchronized void call(){
System.out.println("Call");
}
}
这段代码实例化两个对象,但是因为两个同步方法是static的,所以是类锁,效果和上面那个一样
3.一个普通的synchorized和一个带有static的同步方法
package ThreadTest;
import java.util.concurrent.TimeUnit;
public class ThreadTest02 {
public static void main(String[] args) {
Phone phone1 = new Phone();
Phone phone2 = new Phone();
new Thread(()->{
phone1.sendMsg();
}, "A").start();
try {
TimeUnit.SECONDS.sleep(1);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(()->{
phone2.call();
}, "B").start();
}
}
class Phone{
public static synchronized void sendMsg(){
try {
TimeUnit.SECONDS.sleep(4);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Send message!");
}
public synchronized void call(){
System.out.println("Call");
}
}
现在把下面的static删掉,call方法会先执行,因为有两个锁,一个是类锁,一个是对象锁,所以互不影响。
主要是给自己看的,所以肯定会出现很多错误哈哈哈哈哈