zoukankan      html  css  js  c++  java
  • 线程间共享数据的一个样例

    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




  • 相关阅读:
    从零搭建springboot+mybatis逆向工程
    基础SQL总结
    Map集合浅谈
    ArrayList、LinkedList与Vector的区别
    java多线程总结
    P4108 [HEOI2015]公约数数列
    P2168 [NOI2015] 荷马史诗
    正睿 2021 Noip 十连测 Day2
    CF772E Verifying Kingdom
    BZOJ1767 [CEOI2009] Harbingers
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/4056758.html
Copyright © 2011-2022 走看看