大橙子网站建设,新征程启航
为企业提供网站建设、域名注册、服务器等服务
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作用于方法和静态方法区别
创新互联建站技术团队10多年来致力于为客户提供成都网站设计、网站建设、高端网站设计、全网营销推广、搜索引擎SEO优化等服务。经过多年发展,公司拥有经验丰富的技术团队,先后服务、推广了近千家网站,包括各类中小企业、企事单位、高校等机构单位。
测试代码如下所示
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的方法,锁是加载类上,这个类所有的对象竞争一把锁。