1、深入synchronized关键字
锁:
同步代码块:锁住的是对象
(调用这个方法的对象)
同步方法:与同步代码块类似,锁住的是this
Service.java
class Service{
public void fun1(){
synchronized(this){
try{
Thread.sleep(3 * 1000);
}
catch(Exception e){
e.printStackTrace();
}
System.out.println("fun1");
}
}
public void fun2(){
synchronized(this){
System.out.println("fun2");
}
}
}
MyThread1.java
class MyThread1 implements Runnable{
private Service service;
public MyThread1(Service service){
this.service = service;
}
public void run(){
service.fun1();
}
}
MyThread2.java
class MyThread2 implements Runnable{
private Service service;
public MyThread2(Service service){
this.service = service;
}
public void run(){
service.fun2();
}
}
Test.java
class Test{
public static void main(String args[]){
Service service = new Service();
Thread mt1 = new Thread(new MyThread1(service));
Thread mt2 = new Thread(new MyThread2(service));
mt1.start();
mt2.start();
}
}
如果一个线程获得了一个对象的同步锁,那么这个对象上所有被同步的代码其他线程通通不能执行,但是不影响其他非同步的代码。
2、同步方法:
public synchronized void fun1(){
try{
Thread.sleep(3 * 1000);
}
catch(Exception e){
e.printStackTrace();
}
System.out.println("fun1");
}