首页 > 代码库 > (黑马Java多线程与并发库高级应用)05 线程范围内共享变量的概念与作用
(黑马Java多线程与并发库高级应用)05 线程范围内共享变量的概念与作用
如下代码中会出现问题
package cn.itcast.heima2; import java.util.HashMap; import java.util.Random; public class ThreadScopeShareData { private static int data = http://www.mamicode.com/0; private static HashMap<Thread, Integer> threadData = http://www.mamicode.com/new HashMap<>(); public static void main(String[] args) { for (int i = 0; i < 2; i++) { new Thread(new Runnable() { @Override public void run() { // TODO Auto-generated method stub data = http://www.mamicode.com/new Random(System.currentTimeMillis()).nextInt(); System.out.println(Thread.currentThread().getName() + " has put data :" + data); threadData.put(Thread.currentThread(), data); new A().get(); new B().get(); } }).start(); } } static class A { public void get() { int data=http://www.mamicode.com/threadData.get(Thread.currentThread()); System.out.println("A from " + Thread.currentThread().getName() + " has put data :" + data); } } static class B { public void get() { int data=http://www.mamicode.com/threadData.get(Thread.currentThread()); System.out.println("B from " + Thread.currentThread().getName() + " has put data :" + data); } } }
解决方法:
package cn.itcast.heima2; import java.util.HashMap; import java.util.Random; public class ThreadScopeShareData { private static int data = http://www.mamicode.com/0; static long[] seed = new long[] { 12345612, 654321 }; private static HashMap<Thread, Integer> threadData = http://www.mamicode.com/new HashMap<>(); public static void main(String[] args) { new Thread(new ThreadScopeShareData.MyRunnable() { @Override public void run() { // TODO Auto-generated method stub data =http://www.mamicode.com/ MyRunnable.rd.nextInt(); System.out.println(Thread.currentThread().getName() + " has put data :" + data); threadData.put(Thread.currentThread(), data); new A().get(); new B().get(); } }).start(); new Thread(new ThreadScopeShareData.MyRunnable() { @Override public void run() { // TODO Auto-generated method stub data =http://www.mamicode.com/ MyRunnable.rd.nextInt(); System.out.println(Thread.currentThread().getName() + " has put data :" + data); threadData.put(Thread.currentThread(), data); new A().get(); new B().get(); } }).start(); } static class A { public void get() { int data=http://www.mamicode.com/threadData.get(Thread.currentThread()); System.out.println("A from " + Thread.currentThread().getName() + " has put data :" + data); } } static class B { public void get() { int data=http://www.mamicode.com/threadData.get(Thread.currentThread()); System.out.println("B from " + Thread.currentThread().getName() + " has put data :" + data); } } abstract static class MyRunnable implements Runnable { static Random rd = new Random(); public abstract void run(); } }
(黑马Java多线程与并发库高级应用)05 线程范围内共享变量的概念与作用
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。