个人的一点理解,表述的有可能不是很准确。
对象锁,顾名思义,锁住当前对象,又叫方法锁。不同对象实例的锁互不影响。用一个Demo来说明:
public class Task {
private Object lock=new Object();
public void out(){
System.out.println("current thread is:"+Thread.currentThread().getName());
synchronized (lock) {
System.out.println(Thread.currentThread().getName()+" is working....");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" finish work");
}
}
}
工作线程:
public class MyThread extends Thread {
private Task task;
public MyThread(String name,Task task){
super(name);
this.task=task;
}
@Override
public void run() {
super.run();
task.out();
}
}
public class Test {
public static void main(String[] args) {
Task task=new Task();
MyThread thread1=new MyThread("thread1", task);
MyThread thread2=new MyThread("thread2", task);
thread1.start();
thread2.start();
}
}
第一种:如上main函数中,两个线程访问同一个对象的out方法,同步执行。也就是说一个线程执行结束后另一个线程才会执行。同一个对象同一把锁。
打印输出:
current thread is:thread1
current thread is:thread2
thread1 is working.... //等待5s
thread1 finish work
thread2 is working.... //等待5s
thread2 finish work
第二种:如上main函数中,两个线程访问不同对象的out方法,不同步执行。两个线程调用的是不同的对象锁,互不影响。
打印输出:
current thread is:thread1
current thread is:thread2
thread1 is working.... //同时输出, 等待5s
thread2 is working.... //同时输出 ,等待5s
thread1 finish work
thread2 finish work
代码中的 synchronized (lock) {....}也可用 synchronized (this) {....}替代
或者用synchronized修饰out(), public synchronized void out()
类锁,不管多少对象都共用同一把锁,同步执行,一个线程执行结束、其他的才能够调用同步的部分。
public class Task {
private Object lock=new Object();
public synchronized void out(){
System.out.println("current thread is:"+Thread.currentThread().getName());
synchronized (Task.class) {
System.out.println(Thread.currentThread().getName()+" is working....");
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" finish work");
}
}
}
public class Test {
public static void main(String[] args) {
Task task=new Task();
Task task1=new Task();
MyThread thread1=new MyThread("thread1", task);
MyThread thread2=new MyThread("thread2", task1);
thread1.start();
thread2.start();
}
}
打印输出:
current thread is:thread1
current thread is:thread2
thread1 is working.... //等待5s
thread1 finish work
thread2 is working.... //等待5s
thread2 finish work
synchronized (Task.class) { ...}也可用public static synchronized void out(){....}代替。
打印输出:
current thread is:thread1
thread1 is working.... //等待5s
thread1 finish work
current thread is:thread2
thread2 is working.... //等待5s
thread2 finish work