Creating, running, and setting the characteristics of a thread

In this recipe, we will learn how to do basic operations over a thread using the Java API. As with every element in the Java language, threads are objects. We have two ways of creating a thread in Java:

  • Extending the Thread class and overriding the run() method.
  • Building a class that implements the Runnable interface and the run() method and then creating an object of the Thread class by passing the Runnable object as a parameter--this is the preferred approach and it gives you more flexibility.

In this recipe, we will use the second approach to create threads. Then, we will learn how to change some attributes of the threads. The Thread class saves some information attributes that can help us identify a thread, know its status, or control its priority. These attributes are:

  • ID: This attribute stores a unique identifier for each thread.
  • Name: This attribute stores the name of the thread.
  • Priority: This attribute stores the priority of the Thread objects. In Java 9, threads can have priority between 1 and 10, where 1 is the lowest priority and 10 is the highest. It's not recommended that you change the priority of the threads. It's only a hint to the underlying operating system and it doesn't guarantee anything, but it's a possibility that you can use if you want.
  • Status: This attribute stores the status of a thread. In Java, a thread can be present in one of the six states defined in the Thread.State enumeration: NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, or TERMINATED. The following is a list specifying what each of these states means:
    • NEW: The thread has been created and it has not yet started
    • RUNNABLE: The thread is being executed in the JVM
    • BLOCKED: The thread is blocked and it is waiting for a monitor
    • WAITING: The thread is waiting for another thread
    • TIMED_WAITING: The thread is waiting for another thread with a specified waiting time
    • TERMINATED: The thread has finished its execution

In this recipe, we will implement an example that will create and run 10 threads that would calculate the prime numbers within the first 20,000 numbers.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.36.38