• 线程间共享数据的一个样例


    package com.wsy.model;
    
    
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Random;
    
    
    public class ThreadScopeShareData {
    	private static Map<Thread, Integer> threadDataMap = new HashMap<Thread, Integer>();
    
    
    	public static void main(String[] args) {
    		final A a = new A();
    		final B b = new B();
    
    
    		for (int i = 0; i < 2; i++) {
    			new Thread(new Runnable() {
    				@Override
    				public void run() {
    					int data = new Random().nextInt();
    					System.out.println(Thread.currentThread() + " data is "
    							+ data);
    					threadDataMap.put(Thread.currentThread(), data);
    					a.getData();
    					b.getData();
    				}
    			}).start();
    		}
    	}
    
    
    	static class A {
    
    
    		public void getData() {
    			System.out.println("A: data is "
    					+ threadDataMap.get(Thread.currentThread()) + " of "
    					+ Thread.currentThread().getName());
    		}
    
    
    	}
    
    
    	static class B {
    		public void getData() {
    			System.out.println("B: data is "
    					+ threadDataMap.get(Thread.currentThread()) + " of "
    					+ Thread.currentThread().getName());
    		}
    	}
    }


    输出结果:

    Thread[Thread-0,5,main] data is 160847734
    Thread[Thread-1,5,main] data is 1298550232
    A: data is 1298550232 of Thread-1
    A: data is 160847734 of Thread-0
    B: data is 160847734 of Thread-0
    B: data is 1298550232 of Thread-1




  • 相关阅读:
    JAVA学习25天
    Java学习第24天
    Java学习第23天
    Java学习22天
    第3周
    Java21
    day23作业
    day23
    Typecho使用技巧
    搭建Typecho博客
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/4056758.html
Copyright © 2020-2023  润新知