Follow these steps to implement the example:
- First, implement a program that has the problem exposed previously. Create a class called UnsafeTask and specify that it implements the Runnable interface. Declare a private java.util.Date attribute:
public class UnsafeTask implements Runnable{ private Date startDate;
- Implement the run() method of the UnsafeTask object. This method will initialize the startDate attribute, write its value to the console, sleep for a random period of time, and again write the value of the startDate attribute:
@Override public void run() { startDate=new Date(); System.out.printf("Starting Thread: %s : %s\n", Thread.currentThread().getId(),startDate); try { TimeUnit.SECONDS.sleep( (int)Math.rint(Math.random()*10)); ...