| 1 | import java.util.concurrent.ThreadLocalRandom; |
| 2 | |
| 3 | public class ThreadJob implements Runnable { |
| 4 | |
| 5 | ThreadJob(String name) { |
| 6 | setName(name); |
| 7 | } |
| 8 | |
| 9 | public void setName(String name) { |
| 10 | Thread.currentThread().setName(name); |
| 11 | } |
| 12 | |
| 13 | public void run() { |
| 14 | for (int j = 0; j < 10; j++) { |
| 15 | int sleep_time = ThreadLocalRandom.current().nextInt(201); |
| 16 | try { |
| 17 | Thread.sleep(sleep_time); |
| 18 | } |
| 19 | catch(InterruptedException e) { |
| 20 | // this part is executed when an exception (in this example InterruptedException) occurs |
| 21 | System.err.println("InterruptedException: " + e); |
| 22 | } |
| 23 | String threadName = Thread.currentThread().getName(); |
| 24 | System.out.println(threadName + " has slept for " + sleep_time + " ms for the " + (j + 1) + " times"); |
| 25 | } |
| 26 | } |
| 27 | } |