Java synchronized
日期: 2019-03-19 分类: 个人收藏 321次阅读
@ synchronized
synchronized同步锁
四种方式
1 类锁
主要用在单例
private static volatile MyManager instance;
public static MyManager getInstance() {
if (instance == null) {
synchronized (MyManager.class) {
if(instance==null){
instance = new MyManager();
}}
}
return instance;
}
2 静态方法锁
public static synchronized void addCount3() {
for (int i = 0; i < 100; i++) {
count++;
System.out.println(Thread.currentThread().getName() + "----" + count);
}
}
静态方法锁锁住的是类,对此类创建的对象都互斥
3 方法锁
public synchronized void addCount2() {
for (int i = 0; i < 100; i++) {
count++;
System.out.println(Thread.currentThread().getName() + "----" + count);
}
}
这种锁只在当前类中互斥
4代码块锁
public void addCount() {
synchronized (this) {
for (int i = 0; i < 100; i++) {
count++;
System.out.println(Thread.currentThread().getName() + "----" + count);
}
}
}
synchronized (this) 括号中可以是任意对象,锁住的是括号中的对象。
完整代码
private static int count = 0;
private static volatile MyManager instance;
public static MyManager getInstance() {
public class MyManager {
if (instance == null) {
synchronized (MyManager.class) {
instance = new MyManager();
}
}
return instance;
}
public void addCount() {
synchronized (this) {
for (int i = 0; i < 100; i++) {
count++;
System.out.println(Thread.currentThread().getName() + "----" + count);
}
}
}
public synchronized void addCount2() {//只限本类中互斥
for (int i = 0; i < 100; i++) {
count++;
System.out.println(Thread.currentThread().getName() + "----" + count);
}
}
public static synchronized void addCount3() {
for (int i = 0; i < 100; i++) {
count++;
System.out.println(Thread.currentThread().getName() + "----" + count);
}
}
@Test
public void main() {
new Thread(new Run1()).start();
new Thread(new Run2()).start();
}
class Run1 implements Runnable {
@Override
public void run() {
MyManager.getInstance().addCount2();
}
}
class Run2 implements Runnable {
@Override
public void run() {
MyManager.getInstance().addCount2();
}
}}
在其他类中调用方法2
public class SynchronizedTest {
@Test
public void main() {
new Thread(new Run1()).start();
new Thread(new Run2()).start();
}
class Run1 implements Runnable {
@Override
public void run() {
MyManager.getInstance().addCount2();
}
}
class Run2 implements Runnable {
@Override
public void run() {
MyManager.getInstance().addCount2();
}
}}
亲自试试,在SynchronizedTest类中开启俩个线程调用addCount2()并没有互斥。
除特别声明,本站所有文章均为原创,如需转载请以超级链接形式注明出处:SmartCat's Blog
标签:Java
精华推荐