Multithreading Creating a Thread in JAVA - Java2021 : Online Tutorials Hub

Java2021 : Online Tutorials Hub

JAVA | Advance Java | MySQL | Data Structure | Git | HTML | CSS | JS

Latest

Post Top Ad

Monday, July 6, 2020

Multithreading Creating a Thread in JAVA

How to create a thread in java
we have two ways to creating a thread in java
  1. Using Thread Class
  2. Using Runnable Interface
When we use thread class : we have methods and constructor and we can used.click here
When we use Runnable interface :  only one method : run();

Creating a thread using Extending Thread Class : 
public class All extends Thread {
    public void run(){
        System.out.println("Thread is running using thread class");
    }
    public static void main(String[] args)
    {
        All all=new All();
        all.run();
    }
}
Output : 





Creating a thread using Runnable Interface : 

class A1 implements Runnable
{
    public void run(){
        System.out.println("Thread is running using runnable interface");
    }
    public static void main(String[] args)
    {
        A1 a1=new A1();
        Thread t1=new Thread(a1);
        t1.start();
    }
}
Output : 

Note  : We cannot run a thread twice if we doing this exception are thrown (IllegalThreadStateException)

Example : 
class TwiceThread extends Thread{
    public void run(){
        System.out.println("Never run twice thread");
    }
    public static void main(String[] args) {
        TwiceThread t1=new TwiceThread();
        t1.start();
        t1.start();
    }
}
Output : 
// t1.start() first time execute



//t1.start() second time execute





Sorting and Searching Programs
Start with your Choice
-Important Programs for Freshers
Learn Pattern Programs 
Click to learn Array Programs
Click to Learn MySQL 
for any complaint regarding my Blog please visit contact us page and write what problem you have!

No comments:

Pages