1 2 3 of Threads in Java

1 2 3 of Threads in Java

What you will find here is the basics of Java threads so you do not want to procrastinate about threads and start using them.

As always we start with what official documentation has to say about it,

A thread is a thread of execution in a program. The Java Virtual Machine allows an application to have multiple threads of execution running concurrently. Every thread has a priority.

Threads with higher priority are executed in preference to threads with lower priority. Each thread may or may not also be marked as a daemon. When code running in some thread creates a new Thread object, the new thread has its priority initially set equal to the priority of the creating thread and is a daemon thread if and only if the creating thread is a daemon.

When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class). The Java Virtual Machine continues to execute threads until either of the following occurs: The exit method of class Runtime has been called and the security manager has permitted the exit operation to take place. All threads that are not daemon threads have died, either by returning from the call to the run method or by throwing an exception that propagates beyond the run method.


Create a Thread

Create a thread - method 1

 class PrimeThread extends Thread {
           long minPrime;
           PrimeThread(long minPrime) {
               this.minPrime = minPrime;
           }

           public void run() {
               // compute primes larger than minPrime
                . . .
           }
 }
 PrimeThread p = new PrimeThread(143);
 p.start();

Create a thread - method2

 class PrimeRun implements Runnable {
           long minPrime;
           PrimeRun(long minPrime) {
               this.minPrime = minPrime;
           }

           public void run() {
               // compute primes larger than minPrime
                . . .
           }
}
PrimeRun p = new PrimeRun(143);
new Thread(p).start();

Creating Daemon thread

Daemon threads are low-priority threads which do not interrupt JVM termination and are ideal for housekeeping jobs like garbage collection

PrimeThread p = new PrimeThread(143);
p.setDaemon(true);
p.start();