线程的互斥与同步通信

来源:互联网 发布:网络教育心理学专业 编辑:程序博客网 时间:2024/05/17 05:19

synchronized的使用和wait与notify实现线程间的通信

案例: 子线程循环10次, 主线程循环5次, 两者交替运行50次

代码
package thread;public class TraditionalThreadCommunication {public static void main(String[] args) {final Bussiness bussiness = new Bussiness();new Thread(new Runnable() {@Overridepublic void run() {for (int i = 1; i <= 50; i++) {bussiness.sub(i);}}}).start();for (int i = 1; i <= 50; i++) {bussiness.main(i);}}}class Bussiness {private boolean flag = true;public synchronized void sub(int j) {// 如果flag为false则等待while (!flag) {// 使用while 比较好 可以防止假唤醒try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}for (int i = 1; i <= 10; i++) {System.out.println("sub : " + i + " 第" + j + "次外循环");}// 将flag置为false 并唤醒主线程flag = false;this.notify();}public synchronized void main(int j) {// 如果flag为true则等待while (flag) {try {this.wait();} catch (InterruptedException e) {e.printStackTrace();}}for (int i = 1; i <= 5; i++) {System.out.println("main : " + i + " 第" + j + "次外循环");}// 将flag置为true 并唤醒子线程flag = true;this.notify();}}

将需要互斥的资源(属性和方法) 统一定义在一个类中, 而不是将互斥代码写到线程中, 这样做的好处是以后任何线程再访问资源类的时候就可以保证是线程安全的

注意: 使用notify()和notifyAll()方法的时候是不会释放锁资源的


原创粉丝点击