1.线程同步
package com.test.synchronizeds;//线程同步public class TraditionThreadSynchronized { public void init(){ final Outputer o=new Outputer(); //线程1 new Thread(new Runnable() { @Override public void run() { while(true){ try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } o.output1("chenxiaobing"); } } }).start(); //线程2 new Thread(new Runnable() { @Override public void run() { while(true){ try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } o.output1("donyanxia"); } } }).start(); } public static void main(String[] args) { new TraditionThreadSynchronized().init(); } static class Outputer{ //方法1 public void output1(String name){ int len=name.length(); synchronized(this){ //钥匙必须相同 :synchronized中的的变量,必须是针对所有线程来讲都是一样的,此时才能打达到线程同步的效果. for(int i=0;i
2.线程同步、交互
package com.test.synchronizeds;/** * 子线程循环10次,主线程循环20次,子线程循环10次,主线程循环20次,如此交替循环50次 * @author Administrator * */public class TraditionThreadCommunication { public static void main(String[] args) { final Bussines b=new Bussines(); //子线程 new Thread(new Runnable() { @Override public void run() { for(int i=1;i<=50;i++){ b.sub(i); } } }).start(); //主线程 for(int i=1;i<=50;i++){ b.main(i); } } static class Bussines{ private boolean bshouldsub=true; public synchronized void main(int loop){ while(bshouldsub){ try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } for(int i=1;i<=20;i++){ System.out.println("main thread sequece of"+i+" loop of"+loop); } bshouldsub = true; this.notify(); } public synchronized void sub(int loop){ while(!bshouldsub){ try { this.wait(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } for(int i=1;i<=10;i++){ System.out.println("sub thread sequece of"+i+" loop of"+loop); } bshouldsub = false; this.notify(); } }}