标签:
线程互斥是指某一资源同时只允许一个访问者对其进行访问,具有唯一性和排它性。但互斥无法限制访问者对资源的访问顺序,即访问是无序的。
子线程循环10次,接着主线程循环100次,接着又回到子线程循环10次,接着在回到主线程循环100次,如此循环50次,请写出程序。
package cn.itcast.heima2; public class TraditionalThreadCommuniction { public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { for (int j = 1; j <= 50; j++) {<span style="font-family: Arial, Helvetica, sans-serif;">//子程序循环50次</span> for (int i = 1; i <= 10; i++) {//执行10次输出子程序 System.out.println("sub sthread sequece of " + i + ",loop of" + j); } } } }).start(); for (int j = 1; j <= 50; j++) {//主程序循环50次 for (int i = 1; i <= 100; i++) {//执行100次输出主程序 System.out.println("main sthread sequece of " + i + ",loop of" + j); } } } }执行结果如下,从结果中,我们可以看到,这并不是我们要的结果。
package cn.itcast.heima2; public class TraditionalThreadCommuniction { public static void main(String[] args) { new Thread(new Runnable() { @Override public void run() { for (int j = 1; j <= 50; j++) { synchronized (TraditionThradSynchronized.class) { for (int i = 1; i <= 10; i++) { System.out.println("sub sthread sequece of " + i + ",loop of" + j); } } } } }).start(); for (int j = 1; j <= 50; j++) { synchronized (TraditionThradSynchronized.class) { for (int i = 1; i <= 100; i++) { System.out.println("main sthread sequece of " + i + ",loop of" + j); } } } } }
package cn.itcast.heima2; public class TraditionalThreadCommunictionn { public static void main(String[] args) { final Business business= new Business(); new Thread(new Runnable() { @Override public void run() { for (int j = 1; j <= 50; j++) { business.sub(j); } } }).start(); for (int j = 1; j <= 50; j++) { business.main(j); } } } class Business{ private boolean bshouldSub = true;//子线程和主线程通信信号 public synchronized void sub(int j){ if(!bshouldSub){ try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int i = 1; i <= 10; i++) { System.out.println("sub sthread sequece of " + i + ",loop of" + j); } bshouldSub = false;//运行结束,设置值为FALSE 让主程序运行 this.notify();//唤醒等待的程序 } public synchronized void main(int j){ if(bshouldSub){//如果bshouldsub=true ,等待 让子程序运行 try { this.wait(); } catch (InterruptedException e) { e.printStackTrace(); } } for (int i = 1; i <= 100; i++) { System.out.println("main sthread sequece of " + i + ",loop of" + j); } bshouldSub = true;//让子程序运行 this.notify();//唤醒等待的一个程序 } }
多线程同步互斥实例——使用synchronized实现线程通信和互斥
标签:
原文地址:http://blog.csdn.net/lu930124/article/details/51242382