
上QQ阅读APP看书,第一时间看更新
2.2.4 一半异步,一半同步
本示例用于说明不在synchronized代码块中就是异步执行,在synchronized代码块中就是同步执行。
创建t7项目,文件Task.java代码如下:
package mytask; public class Task { public void doLongTimeTask() { for (int i = 0; i < 100; i++) { System.out.println("nosynchronized threadName=" + Thread.currentThread().getName() + " i=" + (i + 1)); } System.out.println(""); synchronized (this) { for (int i = 0; i < 100; i++) { System.out.println("synchronized threadName=" + Thread.currentThread().getName() + " i=" + (i + 1)); } } } }
两个线程类代码如图2-23所示。

图2-23 两个线程代码
文件Run.java代码如下:
package test; import mytask.Task; import mythread.MyThread1; import mythread.MyThread2; public class Run { public static void main(String[] args) { Task task = new Task(); MyThread1 thread1 = new MyThread1(task); thread1.start(); MyThread2 thread2 = new MyThread2(task); thread2.start(); } }
程序运行结果如图2-24所示。

图2-24 非同步时交叉输出
进入synchronized代码块后被排队执行,结果如图2-25所示。

图2-25 排队执行