多线程同步:多个线程共同协作正确的执行任务。
我们经常见到多线程同步关键字synchronized,那它到底是利用谁做同步锁呢。
要想实现多线程同步,必须要保证同步锁是共享唯一的。
synchronized一般用于3中场景:
1.非静态方法
2.静态方法
3.代码块
一、非静态方法
同步锁指当前方法所在的对象实例,如果对象是单例,则可以实现线程同步。
public synchronized void run() {
for (int start =1; start < 10; start++) {
System.out.println("No." + threadNo + ":" + start);
}
}
二、静态方法
同步锁指当前方法所在的类,类是唯一的,所以一定可以实现线程同步。
public static synchronized void test(){
System.out.println("test");
}
三、代码块
同步锁可以自定义,但要保证是唯一。
public void run() {
synchronized (this) {
for (int start = 1; start < 20; start++) {
System.out.println("No." + threadNo + ":" + start);
}
}
}
这里的this,指当前方法所在类的实例,如果是单例,就是唯一的。