java thread tutorial code 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: 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 5: multithreading in java
class Count implements Runnable
{
Thread mythread ;
Count()
{
mythread = new Thread(this, "my runnable thread");
System.out.println("my thread created" + mythread);
mythread.start();
}
public void run()
{
try
{
for (int i=0 ;i<10;i++)
{
System.out.println("Printing the count " + i);
Thread.sleep(1000);
}
}
catch(InterruptedException e)
{
System.out.println("my thread interrupted");
}
System.out.println("mythread run is over" );
}
}
class RunnableExample
{
public static void main(String args[])
{
Count cnt = new Count();
try
{
while(cnt.mythread.isAlive())
{
System.out.println("Main thread will be alive till the child thread is live");
Thread.sleep(1500);
}
}
catch(InterruptedException e)
{
System.out.println("Main thread interrupted");
}
System.out.println("Main thread run is over" );
}
}
Example 6: multithreading in java simple example
class MultithreadingDemo extends Thread{
public void run(){
System.out.println("My thread is in running state.");
}
public static void main(String args[]){
MultithreadingDemo obj=new MultithreadingDemo();
obj.start();
}
}