创建一个线程
2018-10-15 本文已影响0人
writeanewworld
1.示例
/**
* java线程类也是一个object类,他的实例都继承自java.lang.Thread或其子类
* Thread thread = new Thread();
* thread.start();
* @author user
*
*/
public class CreateAThread {
public static void main(String[] args) {
//启动第一个线程
FirstThred th = new FirstThred();
th.start();
System.out.println(th.currentThread());
System.out.println(th.currentThread().getName());
//创建一个Thread的匿名子类
Thread thread = new Thread() {
public void run() {
System.out.println("Thread is run");
}
};
thread.start();
System.out.println(thread.currentThread());
//启动第二个线程 为了使线程能够执行run方法,需要在Thread类的构造函数中传入SecondThread的实例对象
Thread tht = new Thread(new SecondThread());
tht.start();
System.out.println(th.currentThread());
//创建一个实现了Runnable接口的匿名类
Runnable myRunnable = new Runnable() {
public void run() {
System.out.println("Runnable is run");
}
};
Thread tt = new Thread(myRunnable);
tt.start();
System.out.println(tt.currentThread());
}
}
//在类中创建一个线程 1
class FirstThred extends Thread{
public void run() {
System.out.println("Firest Thread is Running");
}
}
//在类中创建一个线程 2
class SecondThread implements Runnable{
public void run() {
System.out.println("Second Thread is Running");
}
}