xxxxxxxxxx
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();
}
}
xxxxxxxxxx
public class MyThread extends Thread {
private final String name;
public MyThread(String name) {
this.name = name;
}
public void run() {
try {
for (; ; ) {
System.out.println(name);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("sleep interrupted");
}
}
public static void main(String[] args) {
Thread t1 = new MyThread("First Thread");
Thread t2 = new MyThread("Second Thread");
t1.start();
t2.start();
}
}
xxxxxxxxxx
//if your project supports java8, you can implement with lambda function
//for android
new Thread(() -> {
// do background stuff here
runOnUiThread(()->{
// OnPostExecute stuff here
});
}).start();
xxxxxxxxxx
class SoftHuntThread
{
public static void main(String argvs[])
{
Thread thread= new Thread("Softhunt Thread");
thread.start();
String string = thread.getName();
System.out.println(string);
}
}
In Java, a thread is a lightweight process that runs within another
process or thread. It is an independent path of execution in an
application. Each thread runs in a separate stack frame.
By default Java starts one thread when the main method of a class is
called
xxxxxxxxxx
public class Main extends Thread {
public static int amount = 0;
public static void main(String[] args) {
Main thread = new Main();
thread.start();
// Wait for the thread to finish
while(thread.isAlive()) {
System.out.println("Waiting...");
}
// Update amount and print its value
System.out.println("Main: " + amount);
amount++;
System.out.println("Main: " + amount);
}
public void run() {
amount++;
}
}
xxxxxxxxxx
public static void main(String[] args {
Thread t1= new Thread( );
t1.start();
}
xxxxxxxxxx
class Java_Thread extends Thread{
public void run(){
System.out.println("thread is running...");
}
public static void main(String args[]){
Java_Thread thread =new Java_Thread ();
thread.start();
}
}