Java 提供了三种创建线程的方法:
- 通过实现 Runnable 接口;
- 通过继承 Thread 类本身;
- 通过 Callable 和 Future 创建线程
这里只说一下前两种方法。
一、实现Runnable 接口
要实现Runnable接口,类只需要重写run()方法,run() 可以调用其他方法,使用其他类,并声明变量,就像主线程一样,声明如下:
public void run()
新线程创建之后,你调用它的 start() 方法它才会运行。
void start();
示例:
public class RunnableDemo implements Runnable{
private Thread t;
private String ThreadName;
public RunnableDemo(String threadName) {
System.out.println("Create Thread:"+threadName);
ThreadName = threadName;
}
public RunnableDemo() {
}
@Override
public void run() {
System.out.println("Running Thread:"+ThreadName);
for(int i=4;i>0;i--){
System.out.println("Thread:"+ThreadName+" "+i);
}
System.out.println("Thread:"+ThreadName+" exiting");
}
public Thread getT() {
return t;
}
public void setT(Thread t) {
this.t = t;
}
public String getThreadName() {
return ThreadName;
}
public void setThreadName(String threadName) {
ThreadName = threadName;
}
public void start(){
System.out.println("Start Thread:"+ThreadName);
if(t==null){
t = new Thread(this,ThreadName);
t.start();
}
}
}
public class ThreadTest {
public static void main(String[] args){
RunnableDemo demo1 = new RunnableDemo("Thread -1");
demo1.start();
RunnableDemo demo2 = new RunnableDemo("Thread -2");
demo2.start();
}
}
执行结果:
二、继承Thread类
创建一个新的类,该类继承 Thread 类,然后创建一个该类的实例。
继承类必须重写 run() 方法,该方法是新线程的入口点。它也必须调用 start() 方法才能执行。
示例:
public class ThreadDemo extends Thread {
private Thread t;
private String threadName;
public ThreadDemo(String threadName){
System.out.println("Create Thread:"+threadName);
this.threadName = threadName;
}
public void run() {
System.out.println("Running " + threadName );
try {
for(int i = 4; i > 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// 让线程睡眠一会
Thread.sleep(50);
}
}catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start () {
System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}
本质上也是实现Runnable接口,因为Thread类本身实现了Runnable接口
Thread类一些重要的方法:
方法 | 描述 |
---|---|
public void start() | 使该线程开始执行;Java 虚拟机调用该线程的 run 方法 |
public void run() | 如果该线程是使用独立的 Runnable 运行对象构造的,则调用该 Runnable 对象的 run 方法;否则,该方法不执行任何操作并返回 |
public final void setName(String name) | 改变线程名称,使之与参数 name 相同 |
public final void setPriority(int priority) | 更改线程的优先级 |
public final void setDaemon(boolean on) | 将该线程标记为守护线程或用户线程 |
public final void join(long millisec) | 等待该线程终止的时间最长为 millis 毫秒 |
public void interrupt() | 中断线程 |
public final boolean isAlive() | 测试线程是否处于活动状态 |
Thread 类的静态方法
方法 | 描述 |
---|---|
public static void yield() | 暂停当前正在执行的线程对象,并执行其他线程 |
public static void sleep(long millisec) | 在指定的毫秒数内让当前正在执行的线程休眠(暂停执行),此操作受到系统计时器和调度程序精度和准确性的影响 |
public static boolean holdsLock(Object x) | 当且仅当当前线程在指定的对象上保持监视器锁时,才返回 true |
public static Thread currentThread() | 返回对当前正在执行的线程对象的引用 |
public static void dumpStack() | 将当前线程的堆栈跟踪打印至标准错误流 |