public class MyJava{
public static void main(String[] args){
String[] strs=new String[2];
MyThread_A t1=new MyThread_A(strs);
MyThread_B t2=new MyThread_B(strs);
t1.start();
t2.start();
for(String s:strs) System.out.println(s); //打印每个线程收集的数据
}
}class MyThread_A extends Thread{
String[] strs;
public MyThread_A(String[] strs){
this.strs=strs;
}
public void run(){
String s=null; //计算机strs[0]的值
s="a";
strs[0]=s;
}
}class MyThread_B extends Thread{
String[] strs;
public MyThread_B(String[] strs){
this.strs=strs;
}
public void run(){
String s=null;
s="b"; //计算机strs[1]的值
strs[1]=s;
}
}
public static void main(String[] args){
String[] strs=new String[2];
MyThread_A t1=new MyThread_A(strs);
MyThread_B t2=new MyThread_B(strs);
t1.start();
t2.start();
for(String s:strs) System.out.println(s); //打印每个线程收集的数据
}
}class MyThread_A extends Thread{
String[] strs;
public MyThread_A(String[] strs){
this.strs=strs;
}
public void run(){
String s=null; //计算机strs[0]的值
s="a";
strs[0]=s;
}
}class MyThread_B extends Thread{
String[] strs;
public MyThread_B(String[] strs){
this.strs=strs;
}
public void run(){
String s=null;
s="b"; //计算机strs[1]的值
strs[1]=s;
}
}
你的只是对局部变量的值进行了修改。java是值传递,所以你传的strs在线程中只是对该strs的值的引用,但是并不能改变strs中的值。
public static void main(String[] args)throws InterruptedException{
String[] strs=new String[2];
MyThread_A t1=new MyThread_A(strs);
MyThread_B t2=new MyThread_B(strs);
t1.start();
t1.join();
t2.start();
t2.join();
for(String s:strs) System.out.println(s); //打印每个线程收集的数据
}
}class MyThread_A extends Thread{
String[] strs;
public MyThread_A(String[] strs){
this.strs=strs;
}
public void run(){
String s=null; //计算机strs[0]的值
s="a";
strs[0]=s;
}
}class MyThread_B extends Thread{
String[] strs;
public MyThread_B(String[] strs){
this.strs=strs;
}
public void run(){
String s=null;
s="b"; //计算机strs[1]的值
strs[1]=s;
}
}不过这样就不是多线程了,等于单线程,不过可以得到你想要的结果.
null2. a
null3. null
b
a
b怎会还出现null呢?能说得详细一点吗
null
null
是因为当你第一个线程和第二个线程执行的同时,主线程也在同步执行,自定义的两个线程还没有执行完毕,已经执行了打印语句,结果当然是空。