I am new to Threads. I am reading Java Concurrency in Practice. I found the following example in the book.
@NotThreadSafe
public class UnSafeSequence
{
private int value;
public int getNext()
{
return value++;
}
}
I wanted to test this code by writing couple of threads(or more) accessing this class to get a feeling of thread safety.
I tried like these, but not sure really 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.
I wanted to test this code by writing couple of threads(or more) accessing this class to get a feeling of thread safety.
If each thread has its own instance of UnSafeSequence
then it won't demonstrate the problem. What you need to do is to create an instance of UnSafeSequence
outside of your MyThread
instances and pass it into 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 you are learning about threads, be sure to read about the ExecutorService
and other great classes. Here's a good tutorial from Sun^H^H^H Oracle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With