I'm trying to write a JUnit test. My problem is that my threads can't see the object I have created in the sequential bit of code (code before starting the threads).
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
}
}
See the comment in the run
method above. My object is null but I want both threads to be able to access the MyClass
object. How come they see null? I tried using a constructor but I think the interface prevented me from passing a parameter to the constructor.
Many thanks.