在Java中线程的使用有两种方式:
1.继承Thread类,实现run()方法。
2.实现Runnable接口。
下面分别使用两种方式创建线程。
1.继承Thread类,实现run()方法:
/**
* 自定义线程继承 Thread
* @author haoran.shu
*
*/
public class PrintThread extends Thread {
private final String threadName = "PrintThread";
@Override
public void run() {
super.run();
System.out.println("thread name --> " + threadName);
}
}
要想开启线程的时候,直接创建线程并调用开启方法就行了。
PrintThread thread = new PrintThread();
thread.start();
2.实现Runnable接口:
/**
* 实现Runnable接口的线程
* @author haoran.shu
*
*/
public class PrintRunnable implements Runnable {
private final String name = "PrintRunnable";
public void run() {
System.out.println("name --> " + name);
}
}
调用的时候,也是创建线程并调用开启的方法就行了。
Thread thread = new Thread(new PrintRunnable());
thread.start();
其实翻看Thread类的源码,不难发现,在Thread类的run()方法中存在下面这段代码
/**
* If this thread was constructed using a separate
* <code>Runnable</code> run object, then that
* <code>Runnable</code> object's <code>run</code> method is called;
* otherwise, this method does nothing and returns.
* <p>
* Subclasses of <code>Thread</code> should override this method.
*
* @see #start()
* @see #stop()
* @see #Thread(ThreadGroup, Runnable, String)
*/
@Override
public void run() {
if (target != null) {
target.run();
}
}
在里面有一个target的变量,这个target就是一个Runnable对象。也就是说我们通过实现Runnable的方式实现的接口,最终也是在Thread类的run()方法中,调用的。
通常在程序中,我们创建线程都是简写的。
new Thread(new Runnable() {
public void run() {
// TODO Auto-generated method stub
}
}).start();
在run()方法中书写我们要执行的逻辑。