threading java code example
Example 1: java thread
public class ClassName extends Thread{
public void run(){
super.run();
}
}
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: threads java
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
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();
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();
}
}
}
Example 5: 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();
}
}
Example 6: create thread java
class RunnableObject implements Runnable {
private Thread t;
private String threadName;
RunnableObject( String name) {
System.out.println("Creating " + threadName );
threadName = name;
t = new Thread (this, threadName);
}
public void run() {
System.out.println("Running " + threadName );
}
public void start () {
System.out.println("Starting " + threadName );
t.start ();
}
}
public class TestThread {
public static void main(String args[]) {
RunnableObject R1 = new RunnableObject( "Thread-1");
R1.start();
}
}