When i use cycle sentence to run two Threads it shows me that problem:java.lang.Thread.run(Thread.java:745) but i figure it out use two methods:\first if i dont run the application just debug it and use breakpoint it would be ok . second based on my demo just has two threads so i could copy this part of code "
new Thread(new Runnable() {
@Override
public void run() {
int data = new Random().nextInt();
System.out.println(Thread.currentThread().getName()
+ " has put data:" + data);
threadDataMap.put(Thread.currentThread(), data);
new A().get();
new B().get();
}
}).start();
"
for twice it would also be ok .
all my demo code is below:
package 多线程;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
public class ThreadScopShareData {
private static int data = 0;
private static Map<Thread,Integer> threadDataMap=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 data = new Random().nextInt();
System.out.println(Thread.currentThread().getName()
+ " has put data:" + data);
threadDataMap.put(Thread.currentThread(), data);
new A().get();
new B().get();
}
}).start();
}
}
static class A {
public void get() {
int data=threadDataMap.get(Thread.currentThread());
System.out.println("A from " + Thread.currentThread().getName()
+ "get data:" + data);
}
}
static class B {
public void get() {
int data=threadDataMap.get(Thread.currentThread());
System.out.println("B from " + Thread.currentThread().getName()
+ "get data:" + data);
}
}
}
and the right result should be like below: Thread-1 has put data :-1188249922 Thread-0 has put data :1024718434 A from Thread-0 get data :1024718434 B from Thread-0 get data :1024718434 A from Thread-1 get data :-1188249922 B from Thread-1 get data :-1188249922
but the bug is below:Thread-1 has put data :-807205084 Thread-0 has put data :-976943511 A from Thread-0 get data :-976943511
Exception in thread "Thread-1" B from Thread-0 get data :-976943511
java.lang.NullPointerException
at 多线程.ThreadScopeShareData$A.get(ThreadScopeShareData.java:33)
at 多线程.ThreadScopeShareData$1.run(ThreadScopeShareData.java:22)
at java.lang.Thread.run(Thread.java:745)
As far as i know the Thread-1 would totally change and kill the thread-0 so it would appear a nullPointerException . but i am not sure.