我在一个类中要获得另一个类中的static 的静态变量, 不过第二个类是一个线程类.我要在线程中为这
个静态的变量赋值 ,然后在第一个类中输出.(可能下面的代码有些问题,这个不重要.基本是这个意思.) public class MyThreadMain{
public static void main(String arg[]){
MyThreadMain thMain=new MyThreadMain();
trMain.getName();
} public void getName(){
MyThread my=new MyThread();
System.out.println("[First Print]Name: "+MyThread.name);
}
}
public class MyThread extends Thread{
public static String name="";
public void run(){
if(name.length==0){
name="OK"
System.out.println("[Second Print]Name: "+name);
}
}
}
个静态的变量赋值 ,然后在第一个类中输出.(可能下面的代码有些问题,这个不重要.基本是这个意思.) public class MyThreadMain{
public static void main(String arg[]){
MyThreadMain thMain=new MyThreadMain();
trMain.getName();
} public void getName(){
MyThread my=new MyThread();
System.out.println("[First Print]Name: "+MyThread.name);
}
}
public class MyThread extends Thread{
public static String name="";
public void run(){
if(name.length==0){
name="OK"
System.out.println("[Second Print]Name: "+name);
}
}
}
MyThread my=new MyThread();
之后,要启动线程:
my.start();
然后在run()中,添加赋值语句啊(正如你所做的name="OK" )最后运行,应该没有问题吧
以上仅供你参考
private static String name ;
public class MyThreadMain{
public static void main(String arg[]){
MyThreadMain thMain=new MyThreadMain();
thMain.getName();
} public void getName(){
MyThread my=new MyThread();
my.start();
try {
my.join();
} catch (InterruptedException e)
{
}
System.out.println("[First Print]Name: "+MyThread.returnName());
}
}
public class MyThread extends Thread{
private static String name="";
public static String returnName()
{
return name;
}
public void run(){
if(name.length()==0){
name="OK";
System.out.println("[Second Print]Name: "+name);
}
}
}
运行结果:
[Second Print]Name: OK
[First Print]Name: OK
public static void main(String arg[]) {
MyThread mt = new MyThread();
mt.start();
try {
mt.join();//让mt执行完了再取name就能保证能取到了
} catch (InterruptedException e) {
e.printStackTrace();
}
MyThreadMain thMain = new MyThreadMain();
thMain.getName();
} public void getName() {
MyThread my = new MyThread();
System.out.println("[First Print]Name: " + MyThread.name);
}
} public class MyThread extends Thread{
public static String name="";
public void run(){
if(name.length()==0 ){
name="OK";
System.out.println("[Second Print]Name: "+name);
}
}
}
class Thread1 extends Thread{
static private int num=0;
public void run(){
int i=0;
while(true){
num=i++;
System.out.println(num+"sub thread");
}
}
public int getNum(){
return num;
}
}
public class Test{
public static void main(String [] args){
Thread1 myThread=new Thread1();
myThread.start();
while(true){
System.out.println(myThread.getNum()+"Main thread");
}
}
}