Java – how do I test non thread safe classes?
•
Java
I'm new to threads I'm reading Java concurrency in practice I found the following examples in the book
@NotThreadSafe public class UnSafeSequence { private int value; public int getNext() { return value++; } }
I want to test this code by writing several threads (or more) that access this class for thread safety
I've tried these, but I'm not sure how to test these examples
class MyThread implemented Runnable { public void run() { //Should I create a new object for UnSafeSequence here ? } }
Thanks for your help.
Solution
If each thread has its own instance of unsafe sequence, it will not prove the problem What you need to do is create an unsafe sequence instance outside the myThread instance and pass it to the constructor of each myThread
UnSafeSequence unsafe = new UnSafeSequence(); ... new Thread(new MyThread(unsafe)).start(); new Thread(new MyThread(unsafe)).start(); ... class MyThread implemented Runnable { private UnSafeSequence unsafe; public MyThread(UnSafeSequence unsafe) { this.unsafe = unsafe; } public void run() { ... unsafe.getNext(); ... } }
While learning threads, be sure to read about executorservice and other excellent classes This is a good tutorial from sun ^ H ^ H ^ H oracle
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码