java并发(4)-synchronized
synchronized主要是用于解决共享资源竞争的问题。因为在多线程开发里面,如果存在一个共享资源只允许在一个特定时刻只能一个任务访问它。那么就需要对该资源加锁,让其他人在这个时刻无法访问该资源。只有等待另一个人释放了才可以下一个人使用。
static synchronized 类锁
下面运行一段代码:
public class MainThread {
public static void main(String[] args) {
MyThread
aMyThread = new MyThread("A-MyThread",1),
bMyThread = new MyThread("B-MyThread",2);
aMyThread.start();
bMyThread.start();
System.out.println("Main Thread run Completed!");
}
}
class MyThread extends Thread {
private String name;
private int call;
public MyThread(String name ,int call) {
this.name = name;
this.call = call;
}
@Override
public void run() {
switch (call) {
case 1:
callA();
break;
case 2:
callB();
break;
}
}
private static synchronized void callA() {
System.out.println("callA is runing");
try {
sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("callA had run");
}
private static synchronized void callB() {
System.out.println("callB is runing");
try {
sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("callB had run");
}
}
输入的结果如下:
callA is runing
Main Thread run Completed!
//等待10秒
callA had run
callB is runing
//等待10秒
callB had run
由上面的结果可以看出,如果是static synchronized的话,那么锁的就是对象。该对象的方法如果添加了static synchronized,那么无论是那个对象,对这些方法的访问都需要等待释放锁。
对象锁
如果把上面代码中的static去掉。那么运行的结果如下:
Main Thread run Completed!
callA is runing
callB is runing
//等待10秒
callA had run
callB had run
这样可以看到,由于两个线程是不同对象,而且调用的是不同的方法。所以不会互相影响。拓展一下,两个不同对象,即使访问的是同一个synchronized方法,也不会互相影响。
如下代码:
public class MainThread {
public static void main(String[] args) {
MainThread mt = new MainThread();
MyThread
aMyThread = new MyThread("A-MyThread",mt),
bMyThread = new MyThread("B-MyThread",mt);
aMyThread.start();
bMyThread.start();
System.out.println("Main Thread run Completed!");
}
public synchronized void callC(String threadname) {
System.out.println("callC is runing:" + threadname);
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("callC had run:" + threadname);
}
}
class MyThread extends Thread {
private String name;
private MainThread mt;
public MyThread(String name ,MainThread mt) {
this.name = name;
this.mt = mt;
}
@Override
public void run() {
mt.callC(name);
}
}
运行结果如下:
Main Thread run Completed!
callC is runing:A-MyThread
callC had run:A-MyThread
//等待10秒
callC is runing:B-MyThread
callC had run:B-MyThread
只有当两个不同线程访问的是同一个对象的synchronized方法的时候,才会需要等待释放锁。