我看你的程序写的不对,你的test1根本没有用到,类和类之间是可以传递参数的,如将你的程序改为如下后,将永远打印“ok”。这里的关键是在test,test1中你都定义了一个局部变量 str,而你在change中调用的str是test中的,所以你看到的结果永远是"no"。
import java.awt.*;
public class test implements Runnable
{
Thread th;
String str=new String("no"); test1 a = null; public test()
{
th=new Thread(this);
th.start();
a=new test1(str);
}
public static void main(String args[])
{
new test();
}
public void run()
{
change();
}
public void change()
{
while(true)
{
System.out.println(a.str);
try
{
Thread.currentThread().sleep(500);
}
catch(Exception e){}
}
}
}class test1
{
String str=new String("");
public test1(String st)
{
str=st;
str="ok";
}
import java.awt.*;
public class test implements Runnable
{
Thread th;
String str=new String("no"); test1 a = null; public test()
{
th=new Thread(this);
th.start();
a=new test1(str);
}
public static void main(String args[])
{
new test();
}
public void run()
{
change();
}
public void change()
{
while(true)
{
System.out.println(a.str);
try
{
Thread.currentThread().sleep(500);
}
catch(Exception e){}
}
}
}class test1
{
String str=new String("");
public test1(String st)
{
str=st;
str="ok";
}
public static void main(String[] args){
String str = new String("Yes");
test1 t = new test1(str);
System.out.println("str === " + str + " \nt.str = " + t.str);
}
}class test1 {
String str=new String("ok");
public test1(String st) {
System.out.println(st + " " + st.hashCode());
st=str;// !!
System.out.println(st + " " + st.hashCode());
}
}