1. 实现Runnable 接口
创建线程的最简单的方法就是创建一个实现Runnable 接口的类,一个类仅需实现一个run()的简单方法。
public class ThreadRunnaber implements Runnable{
Thread t;
ThreadRunnaber(){
t = new Thread(this,"DemoChild");
System.out.println("Child Thread Run"+t);
t.start();
}
public void run() {
try {
for(int i=5;i>0;i--) {
System.out.println("Child Thread: " + i);
Thread.sleep(500);
}
} catch (InterruptedException e) {
System.out.println("Child Thread inerrupted");
}
System.out.println("Exiting child thread.");
}
public static void main(String[] args) {
new ThreadRunnaber();//创建一个子线程
try {
for(int i = 5; i > 0; i--) {
System.out.println("Main Thread: " + i);
Thread.sleep(1000);
}
} catch(InterruptedException e ) {
System.out.println("Main thread interrupted.");
}
System.out.println("Main thread exiting.");
}
}
2.可以继承Thread类。
public class ThreadExtends extends Thread{//继承Thread类
ThreadExtends(){
super("Demo MyThread");
System.out.println(this);
start();
}
public void run(){
for (int i=5;i>0;i--) {
try {
System.out.println("Child Thread GO "+ i);
Thread.sleep(500);
}catch(InterruptedException e){
System.out.println("Child Thrad interrupted");
}
}
System.out.println("Child Thrad Over");
}
public static void main(String[] agrs) {
new ThreadExtends();
for (int i=5;i>0;i--) {
try {
System.out.println("Main Thread GO "+i);
Thread.sleep(1000);
}catch(InterruptedException e){
System.out.println("Main Thrad interrupted");
}
}System.out.println("Main Thrad Over");
}
}
3.多开线程 及判断线程存活 等待子线程结束
public static void main(String[] args) {
ThreadRunnaber tr1= new ThreadRunnaber("one");
ThreadRunnaber tr2= new ThreadRunnaber("two");
ThreadRunnaber tr3= new ThreadRunnaber("three");//创建多线程
if (tr1.t.isAlive())System.out.println(tr1 +" still live");//线程还在执行
if (tr2.t.isAlive())System.out.println(tr2 +" still live");
if (tr3.t.isAlive())System.out.println(tr3 +" still live");
try {
System.out.println("---------------Waiting for child finish -------------------------");
tr1.t.join();
tr2.t.join();
tr3.t.join(); //等待子线程结束
} catch(InterruptedException e ) {
System.out.println("Main thread interrupted.");
}
if ((!tr1.t.isAlive()) && (!tr2.t.isAlive()) && (!tr3.t.isAlive())){
System.out.println("Main thread exiting."); //线程结束
}
}
}