您的位置:首页 > 其它

synchronized关键字小结(一)

2016-06-09 16:34 330 查看
1. synchronized同步方法

1) synchronized修饰方法,表示方法是同步的,当某线程进入并拿到当前整个对象的锁时

a. 其他synchronized方法排队等锁

b. 非synchronized方法可异步执行

示例代码(折叠)

package com.khlin.thread;

public class SynchronizedStatic {

public static void main(String[] args) {
ThreadAAA threadAAA = new ThreadAAA();
threadAAA.setName("ThreadAAA");
threadAAA.start();

try {
Thread.sleep(500L);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

ThreadBBB threadBBB = new ThreadBBB();
threadBBB.setName("ThreadBBB");
threadBBB.start();
}
}

class StaticService {
public synchronized static void methodA()
{
String threadname = Thread.currentThread().getName();

System.out.println("invoking methodA. " + threadname);

try {
Thread.sleep(1000L);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

System.out.println("finish methodA. " + threadname);
}

public synchronized static void methodB()
{
String threadname = Thread.currentThread().getName();

System.out.println("invoking methodB. " + threadname);

System.out.println("finish methodB. " + threadname);
}
}

class ThreadAAA extends Thread {

public void run() {
StaticService.methodA();
}
}

class ThreadBBB extends Thread {

public void run() {
StaticService.methodB();
}
}


View Code
运行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: