ale*_*ale 1 java junit multithreading
我正在尝试编写一个JUnit测试.我的问题是我的线程无法在顺序的代码位(启动线程之前的代码)中看到我创建的对象.
public class MyTest implements Runnable {
private MyClass mc;
/**
* @throws InterruptedException
*/
@Test
public void parallelTest() throws InterruptedException {
this.mc = new MyClass();
Thread thread1 = new Thread(new MyTest());
Thread thread2 = new Thread(new MyTest());
thread1.join();
thread2.join();
thread1.start();
thread2.start();
// TODO the test
}
public void run() {
if(mc != null) {
System.out.println("ph not null");
} else {
System.out.println("ph null"); // THIS CODE GETS EXECUTED
}
// some code
}
}
Run Code Online (Sandbox Code Playgroud)
请参阅上述run方法中的注释.我的对象是null但我希望两个线程都能够访问该MyClass对象.怎么会看到空?我尝试使用构造函数,但我认为接口阻止我将参数传递给构造函数.
非常感谢.
每个可运行的实例都是使用创建的new MyTest().并且MyTest类没有任何构造函数初始化该字段private MyClass mc;.所以它有默认值:null.
每个对象都有自己的实例字段.这是OO的基本原则.
| 归档时间: |
|
| 查看次数: |
127 次 |
| 最近记录: |