当两个并发线程访问同一个对象object中的这个synchronized(this)同步代码块时,一个时间内只能有一个线程得到执行。另一个线程必须等待当前线程执行完这个代码块以后才能执行该代码块。
- public class Thread1 implements Runnable {
- public void run() {
- synchronized(this) { // 同步代码块
- for (int i = 0; i < 5; i++) {
- System.out.println(Thread.currentThread().getName() + " synchronized loop " + i);
- }
- }
- }
- public static void main(String[] args) {
- Thread1 t1 = new Thread1();
- Thread ta = new Thread(t1, "A");
- Thread tb = new Thread(t1, "B");
- ta.start();
- tb.start();
- }
- }
运行结果:
A synchronized loop 0
A synchronized loop 1
A synchronized loop 2
A synchronized loop 3
A synchronized loop 4
B synchronized loop 0
B synchronized loop 1
B synchronized loop 2
B synchronized loop 3
B synchronized loop 4
事实上,当传入一个Runnable target参数给Thread后,Thread的run()方法就会调用target.run(),参考JDK源代码:
- public void run() {
- if (target != null) {
- target.run();
- }
- }
http://blog.csdn.net/sunboy_2050/article/details/7675050
http://blog.csdn.net/aboy123/article/details/38307539