zoukankan      html  css  js  c++  java
  • Java中线程范围内共享问题

    本宝宝新手,勿喷!直接上代码了,

    线程范围内共享问题:各个线程之间共享同一块数据,一个数据损坏就全部损坏,需要的可以运行一下!

    public class Threads {
    private static HashMap<Thread, Integer> data = new HashMap<Thread,Integer>();
    public static void main(String[] args) {
    for (int i = 0; i < 2; i++) {
    new Thread(new Runnable() {

    @Override
    public void run() {
    int value = new Random().nextInt(1000);
    data.put(Thread.currentThread(), value);
    System.out.println("名字是:"+Thread.currentThread().getName()+"数据是:"+value);
    A a1 = new A();
    a1.getData();
    B b1 = new B();
    b1.getData();
    C c = new C();
    c.getDate();
    }
    }).start();
    }
    }
    static class A{
    public void getData(){
    Thread thread = Thread.currentThread();
    int value = data.get(thread);
    System.out.println(thread.getName()+"从A中获取数据"+value);
    }
    }
    static class B{
    public void getData(){
    Thread thread = Thread.currentThread();
    int value = data.get(thread);
    System.out.println(thread.getName()+"从B中获取数据"+value);
    }
    }
    static class C{
    public void getDate() {
    Thread thread = Thread.currentThread();
    int value = data.get(thread);
    System.out.println(thread.getName()+"从C中获取数据"+value);
    }
    }

    }

  • 相关阅读:
    proc文件系统面面谈
    如何创建,增加SWAP?
    使用linux中的fdisk无损坏合并分区
    QEMU+Accelerator
    QEMU网络配置
    Linux主机设NAT
    试用QEMU,安装个FreeBSD 5.3
    QEMU简介
    使用Vesa2
    BugFree介绍
  • 原文地址:https://www.cnblogs.com/zlazm/p/7896486.html
Copyright © 2011-2022 走看看