62,615
社区成员
发帖
与我相关
我的任务
分享
public class CsdnTest1
{
public CsdnTest1()
{
Thread2 t2 = new Thread2();
Thread1 t1 = new Thread1();
t1.start();
t2.start();
}
class Thread1 extends Thread
{
int a1 = 10000;
public int getA1()
{
return a1;
}
public void run()
{
System.out.println("thread t2 a2= "+new CsdnTest1.Thread2().getA2()); // 在这里怎么获得t2.a2
// // t2.getA2();错误
}
}
class Thread2 extends Thread
{
int a2 = 30000;
public int getA2()
{
return a2;
}
public void run()
{
// 在这里怎么获得t1.a1
System.out.println("thread t1 a1= "+new CsdnTest1.Thread1().getA1()); //错误
}
}
public static void main(String[] args)
{
new CsdnTest1();
}
}
public class Test
{
public static void main(String[] args)
{
class Thread1 extends Thread
{
int a1 = 1;
public int getA1()
{
return a1;
}
public void run()
{
//因Thread2是本类的内部类,可以进行实例化等操作。
System.out.println("a2 ="+new Thread2().getA2()); // 实例化一个Thread2对象。
//
}
//把第二个线程类放在了第一个内部. 这样Thraed2是Thread1内部类,在Thread1可以
//对Thread2操作。
class Thread2 extends Thread
{
int a2 = 2;
public int getA2()
{
return a2;
}
public void run()
{
//内部类可以指向外围类,通过外围类对象调用其方法。
System.out.println("a1 ="+ Thread1.this.getA1()); //"Thread1.this"是Thread1对象。
}
}
}
Thread1 t1 = new Thread1(); //实例化Thread1.
Thread1.Thread2 t2=t1.new Thread2(); //实例化Thread2.
t1.start();
t2.start();
}
}