标签:特点 目标变量 乐观锁 原因 独立 使用场景 影响 ade 相同
目录介绍t1.start();
t1.join();
t2.start();
没有设置Timeout参数的Object.wait()
没有设置Timeout参数的Thread.join()
LockSupport.park()
Thread.sleep()
设置了Timeout参数的Object.wai()
设置了Timeout参数的Thread.join()
LockSupport.parkNanos()
LockSupport.parkUntil()
private volatile int a = 0;
for (int x=0 ; x<=100 ; x++){
new Thread(new Runnable() {
@Override
public void run() {
a++;
Log.e("小杨逗比Thread-------------",""+a);
}
}).start();
}
for (int x=0 ; x<=100 ; x++){
new Thread(new Runnable() {
@Override
public void run() {
AtomicInteger atomicInteger = new AtomicInteger(a++);
int i = atomicInteger.get();
Log.e("小杨逗比Thread-------------",""+i);
}
}).start();
}
Synchronize作用于方法和静态方法区别
测试代码如下所示
private void test() {
final TestSynchronized test1 = new TestSynchronized();
final TestSynchronized test2 = new TestSynchronized();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
test1.method01("a");
//test1.method02("a");
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
test2.method01("b");
//test2.method02("a");
}
});
t1.start();
t2.start();
}
private static class TestSynchronized{
private int num1;
public synchronized void method01(String arg) {
try {
if("a".equals(arg)){
num1 = 100;
System.out.println("tag a set number over");
Thread.sleep(1000);
}else{
num1 = 200;
System.out.println("tag b set number over");
}
System.out.println("tag = "+ arg + ";num ="+ num1);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
private static int num2;
public static synchronized void method02(String arg) {
try {
if("a".equals(arg)){
num2 = 100;
System.out.println("tag a set number over");
Thread.sleep(1000);
}else{
num2 = 200;
System.out.println("tag b set number over");
}
System.out.println("tag = "+ arg + ";num ="+ num2);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//调用method01方法打印日志【普通方法】
tag a set number over
tag b set number over
tag = b;num =200
tag = a;num =100
//调用method02方法打印日志【static静态方法】
tag a set number over
tag = a;num =100
tag b set number over
tag = b;num =200
- 在static方法前加synchronized:静态方法属于类方法,它属于这个类,获取到的锁,是属于类的锁。
- 在普通方法前加synchronized:非static方法获取到的锁,是属于当前对象的锁。 [技术博客大总结](https://github.com/yangchong211/YCBlogs)
- 结论:类锁和对象锁不同,synchronized修饰不加static的方法,锁是加在单个对象上,不同的对象没有竞争关系;修饰加了static的方法,锁是加载类上,这个类所有的对象竞争一把锁。
标签:特点 目标变量 乐观锁 原因 独立 使用场景 影响 ade 相同
原文地址:http://blog.51cto.com/11359966/2334743