+92 332 4229 857 99ProjectIdeas@Gmail.com

Threading In Java


Threads in Java:
Two approaches

implementing Interface
Implement the Runnable interface in a class
Provide an implementation for the run() method
Instantiate Thread object by passing runnable object in constructor
Start thread

Extending a class (Inheritance)
Subclass java.lang.Thread
Override the run() method
Instantiate Subclass Thread Object
Start thread



Code

implementing Runnable Interface:
    public class ThreadingExample implements Runnable {
   }
    public void run() {
            // write thread behavior
        // code that will execute by thread
   }
 
      ThreadingExample threadExample =
new ThreadingExample("First");

   Thread thread1 = new Thread(threadExample);
thread1.start();

The following example code shows how to read data from multiple files simultaneously.
import java.io.*;
 public class ThreadReader implements Runnable {
       private String fileName;

       public ThreadReader(String _fileName) {
             this.fileName = _fileName;
       }
       public void run() {
              try {
                     String line = null;
                     BufferedReader br = new BufferedReader(new FileReader(fileName));
                     line = br.readLine();
                       while(line != null) {
                           System.out.println(line);
                           line = br.readLine();
                       }
               } catch (IOException e) {
                    e.printStackTrace();
              }
}

     public static void main(String[] args) {
              ThreadReader tr1 = new ThreadReader("abc1.txt");
              ThreadReader tr2 = new ThreadReader("abc2.txt");
              ThreadReader tr3 = new ThreadReader("abc3.txt");
              Thread t1 = new Thread(tr1);
              Thread t2 = new Thread(tr2);
              Thread t3 = new Thread(tr3);
              t1.start();
              t2.start();
              t3.start();
       }
   }




extending Thread Class (Inheritance):
public class ThreadingExample extends Thread {
   }
       public void run() {
         // write thread behavior
        // code that will execute by thread
   }
ThreadingExample threadExample = new ThreadingExample("First");
   Thread thread1 = new Thread(threadExample);
       thread1.start();

Thread Priorities:


You can set/change thread priority by using any of the 3 predefined constants.
   t1.setPriority(Thread.MAX_PRIORITY) (typically 10)
          t1.setPriority(Thread.NORM_PRIORITY) (typically 5)
          t1.setPriority(Thread.MIN_PRIORITY) (typically 1)


OR any integer value from 1 to 10 can be used as thread priority.




Multithreading:
Multithreading occurs asynchronously, meaning one thread executes independently of the other threads. In this way, threads don’t depend on each other’s execution. In contrast, processes that run synchronously depend on each other. That is, one process waits until the other process terminates before it can execute.
Java enables you to synchronize threads by defining a synchronized method. A thread that is inside a synchronized method prevents any other thread from calling another synchronized method on the same object


Getting/Setting current Thread:
public static void main(String[] args) {
Thread t = Thread.currentThread();
       System.out.println("Current thread: " + t.getName());
       t.setName("This is main Thread");
System.out.println("Renamed Thread: " + t);
}
Output:
Current thread: main
Renamed Thread: Thread[This is main Thread,5,main]


Creating your own thread:
public class Test implements Runnable {
      
       private String threadName;
       Thread thread;
      
       public Test(String _threadName) {
             
              this.threadName = _threadName;
              thread = new Thread(this, threadName);
              thread.start();
       }
      
       public void run() {
            try {
              
              System.out.println("Thread: " + threadName );
               Thread.sleep(1000);
              
            } catch (InterruptedException e ) {
               
              System.out.println("Exception: Thread " + threadName + " interrupted");
             
            }
           
            System.out.println("Terminating thread: " + threadName );
       }
      
       public static void main(String[] args) {
             
              new Test("First");
              new Test("Second");
              new Test("Third");
             
              try {
               
                     Thread.sleep (1000);
                    
             } catch (InterruptedException e) {
                
               System.out.println("Exception: Thread main interrupted.");
              
             }
            
             System.out.println("Terminating thread: main thread.");
       }

}


Output:
Thread: First
Thread: Third
Thread: Second
Terminating thread: main thread
Terminating thread: First
Terminating thread: Third
Terminating thread: Second

Resuming and suspending threads:

public class Test implements Runnable {
      
       Thread thread;
       boolean suspended;
      
       public Test() {
             
              thread = new Thread(this, "Thread");
              suspended = false ;
              thread.start();
       }
      
       public void run() {
                try {
                   for (int i = 0; i < 10; i++) {
                       System.out.println("Thread: " + i ); 
                       Thread.sleep(200);
                    synchronized (this) {
                        while (suspended) {
                        wait();
                     }
                  }
               }
                    
            } catch (InterruptedException e) {
               
                 System.out.println("Thread: interrupted.");
            }
           
            System.out.println("Thread exiting.");
       }
      
       public void suspendThread() {
              suspended = true;
       }
      
       public synchronized void resumeThread() {
              suspended = false;
              notify();
       }
      
       public static void main(String[] args) {
              Test test = new Test();
           try {
                
                Thread.sleep(1000);
                test.suspendThread();
                System.out.println("Thread: Suspended"); 
                Thread.sleep(1000);
                test.resumeThread();
                System.out.println("Thread: Resume");
               
           } catch ( InterruptedException e) {
                e.printStackTrace();
           }
       }
 }

Output:

Thread: 0
Thread: 1
Thread: 2
Thread: 3
Thread: 4
Thread: Suspended
Thread: Resume
Thread: 5
Thread: 6
Thread: 7
Thread: 8
Thread: 9
Thread exiting.

0 comments: