Looking for useful code examples to build your Java applications? 


Multithreading in java is a process of executing multiple threads simultaneously.
Thread is basically a lightweight sub-process, a smallest unit of processing. Multiprocessing and multithreading, both are used to achieve multitasking. But we use multithreading than multiprocessing because threads share a common memory area.

They don't allocate separate memory area so saves memory, and context-switching between the threads takes less time than process. Java Multithreading is mostly used in games, animation etc.

  • In this example, we created 4 different threads and each one of them has a random sleep duration. The output show us these threads are being processed simultaneously. 

/**
* Author : Berk Soysal
* ThreadExample.java
*/

package herrberk;

import java.util.Random;

public class ThreadExample implements Runnable {
  
  String name;
  int time;
  Random r = new Random();
  
  public ThreadExample(String s){
    name=s;
    time= r.nextInt(999);
  }
  
  public void run(){
    try {
      System.out.printf("%s is sleeping for %d \n",name,time);
      Thread.sleep(time);
      System.out.printf("%s just woke up ! \n",name);
    } catch (Exception e) {
      
      System.out.println("Exception");
    }
  }
}




/**
* Author : Berk Soysal
* ThreadMain.java
*/

package herrberk;

public class ThreadMain {
  public static void main(String[] args) {
    
    Thread t1 = new Thread(new ThreadExample("One"));
    Thread t2 = new Thread(new ThreadExample("Two"));
    Thread t3 = new Thread(new ThreadExample("Three"));
    Thread t4 = new Thread(new ThreadExample("Four"));
    
    t1.start();
    t2.start();
    t3.start();
    t4.start();
    
  }
}



Please comment below if you have any questions. Thanks.



Continue Reading Useful Java Code Snippets 5 - A Simple Web Browser in Java

Author:

Software Developer, Codemio Admin


Disqus Comments Loading..