thread java example

Example 1: java thread

public class ClassName extends Thread{
  public void run(){
    super.run();
    //Your Code
  }
}

public class Main{
  public static void main(String[] args){
    ClassName thread = new ClassName();
    thread.start();
  }
}

Example 2: java thread

public static void main(String[] args {
   ...
   Thread t1= new Thread(...);
   t1.start();
   ...
}

Example 3: creating thread in java example

class Multi3 implements Runnable{  
public void run(){  
System.out.println("thread is running...");  
}  
  
public static void main(String args[]){  
Multi3 m1=new Multi3();  
Thread t1 =new Thread(m1);  
t1.start();  
 }  
}

Example 4: stream java example

public class StreamBuilders 
{
     public static void main(String[] args)
     {
         Stream<Integer> stream = Stream.of( new Integer[]{1,2,3,4,5,6,7,8,9} );
         stream.forEach(p -> System.out.println(p));
     }
}

Example 5: start thread java

package com.tutorialspoint;

import java.lang.*;

public class ThreadDemo implements Runnable {

   Thread t;
   ThreadDemo() {
    
      // thread created
      t = new Thread(this, "Admin Thread");
     
      // prints thread created
      System.out.println("thread  = " + t);
      
      // this will call run() function
      System.out.println("Calling run() function... ");
      t.start();
   }

   public void run() {
      System.out.println("Inside run()function");
   }

   public static void main(String args[]) {
      new ThreadDemo();
   }
}

Example 6: threads java

// Copy and test
// They run simultaneously

public static void main(String[] args) {
  		// How to create a thread
        Thread thread = new Thread(new Runnable() {
            @Override
			// Loop running in thread
            public void run() {
                for (int i = 0; i < 20; i++) {
                    System.out.println("Printing plus " + i + " in a worker thread.");
                    try {
                        Thread.sleep(1000);
                    } catch(Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread.start();
  		// Loop running in main thread 
        for (int j = 0; j < 20 ; j++) {
            System.out.println("Printing plus " + j + " in a main thread.");
            try {
                Thread.sleep(900);
            } catch(Exception e) {
                e.printStackTrace();
            }
        }
        }

Tags:

Cpp Example