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.
join
ing beforestart
ing?new
does - and this is quite a problem for a Java programmer. If I were you, I would stay away from threads and testing and for some time - just stick to some basic stuff (writing classes, making instances and objects). If you manage to fix your code (by writingthis
instead ofnew MyTest()
) in the two lines instantiating threads, you will run into deeper problems, as writing correct programs using multiple threads, and testing them, is much, much, much, much harder than that.