线程的同步通信与线程范围内的数据共享问题
线程的同步通信与线程范围内的数据共享问题一、线程的同步通信
什么是线程的同步通信?他有什么作用?这是我们在看到一个新概念时多会想起的两个问题。线程的同步通信就是多个线程在做相关的事或者说在操作同一份数据时,线程之间建立一种互知的通信关系;它的作用是使线程之间能和睦共处,既其中某一线程做完这件事后,再通知另外的线程来做这件事,不出现混乱。如上一篇文章留下的面试问题就是一个很好的线程同步编程案例。下面给出详细的代码,和疑问解释。
public class CommunicationThread {final static Lock lock=new Lock();//实例化内部类public static void main(String args[]){new Thread(new Runnable() {public void run() {for(int i=1;i<=50;i++){lock.son(i);//调用子线程}}}).start();for(int i=1;i<=50;i++){lock.father(i);//调用父线程}}/* * Lock类:将相关的互斥操作放在同一个类中 */static class Lock{boolean flag=true;//两个互斥线程的通信钥匙public synchronized void son(int i){while(!flag){//判断是否是该线程运行,此处也可用if语句,效果相同 //但while语句可避免伪唤醒的情况发生,程序更安全。try {this.wait();//线程等待} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}for(int j=1;j<=10;j++){System.out.println("son:"+j+"of current"+i);}flag=false;this.notify();//唤醒等待中的线程}public synchronized void father(int i){while(flag){try {this.wait();//线程等待} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}}for(int j=1;j<=100;j++){System.out.println("father:"+j+"of current"+i);}flag=true;this.notify();//唤醒等待中的线程}}}
public class ShareData {private static int data=0;//静态全局变量public static void main(String[] args) {for(int i=0;i<2;i++){//创建两个线程new Thread(new Runnable(){public void run() {data=new Random().nextInt();System.out.println(Thread.currentThread().getName()+" has put data:"+data);new A().get();//模块A取得数据new B().get();//模块B取得数据}}).start();//线程开启}}//静态模块Astatic class A{public void get(){System.out.println("A from"+Thread.currentThread().getName()+" get data:"+data);}}//静态模块Bstatic class B{public void get(){System.out.println("B from"+Thread.currentThread().getName()+"get data:"+data);}}}
public class ShareData {//建立哈希表,存取数据private static Map<Thread,Integer> threadData=new HashMap<Thread,Integer>();public static void main(String[] args) {for(int i=0;i<2;i++){//创建两个线程new Thread(new Runnable(){public void run() {intdata=new Random().nextInt();//取得数据System.out.println(Thread.currentThread().getName()+" has put data:"+data);threadData.put(Thread.currentThread(), data);new A().get();//模块A取得数据new B().get();//模块B取得数据}}).start();//线程开启}}//静态模块Astatic class A{public void get(){int data = threadData.get(Thread.currentThread());System.out.println("A from"+Thread.currentThread().getName()+" get data:"+data);}}//静态模块Bstatic class B{int data = threadData.get(Thread.currentThread());public void get(){System.out.println("B from"+Thread.currentThread().getName()+"get data:"+data);}}}