深入synchronized关键字
思路:新建Service 类内含有fun1和fun2函数,全部用同步锁锁住
新建两个线程体分别为MyThread1和MyThread2分别运行fun1和fun2函数,然后新建Test2文件分别新建两个线程。
class Service{
public void fun1(){
synchronized(this){
try{
Thread.sleep(3 * 1000);
}
catch(Exception e){
System.out.println(e);
}
System.out.println("fun1");
}
}
public void fun2(){
synchronized(this){
System.out.println("fun2");
}
}
}
class MyThread1 implements Runnable{
private Service service;
public MyThread1(Service service){
this.service = service;
}
public void run(){
service.fun1();
}
}
class MyThread2 implements Runnable{
private Service service;
public MyThread2(Service service){
this.service = service;
}
public void run(){
service.fun2();
}
}
public class Test2{
public static void main(String[] args){
Service service = new Service();
Thread t1 = new Thread(new MyThread1(service));
Thread t2 = new Thread(new MyThread2(service));
t1.start();
t2.start();
}
}
运行结果可能fun1和fun2先后顺序都有,这个例子是为了表明synchronized同步锁锁住的是this所指向的对象的所有代码而不是一个单纯的代码块,两个线程都是用了同一个对象,直接锁住了代码使的这个对象的其他被同步的代码也无法运行。当去掉下面的同步锁后可以正常运行。不太好的例子。
同步方法
将synchronized放到返回值前
public synchronized void fun1:锁住的还是调用的对象this。