package charpter06;
//MyThread02和MyThread01两个类 相互调用的结果
public class MyThread01 extends Thread {
// 用全局变量传参:形参和实参
private MyThread02 t2;
// 成员方法:成员方法包括set通过成员变量传值
public void setT2(MyThread02 t2) {
this.t2 = t2;
}
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
System.out.println(this.getName() + "----t2----" + i);
try {
// 如果不调用join方法,是不会输出结果的
t2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
------------------------
package charpter06;
//MyThread02和MyThread01两个类 相互调用的结果
public class MyThread02 extends Thread {
private MyThread01 t1;
public void setT1(MyThread01 t1) {
this.t1 = t1;
}
@Override
public void run() {
for (int i = 0; i <= 100; i++) {
System.out.println(getName() + "------t1-----" + i);
try {
//该处不调用join方法是不会输出结果的
t1.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
-----------------
package charpter06;
public class Test {
public static void main(String[] args) {
// 创建对象
MyThread01 thread01 = new MyThread01();
MyThread02 thread02 = new MyThread02();
// 通过调用成员方法传对象
thread01.setT2(thread02);
thread02.setT1(thread01);
thread01.start();
thread02.start();
}
}