- 创建一个类继承Thread类
- 重写该接口的run()方法,该run()方法的方法体是该线程的线程执行体
package SimpleThread;
public class SimpleThread extends Thread {
static int count = 0;
//重写run方法, 具体业务逻辑的实现
@Override
public void run() {
while(true) {
System.out.println("Hello: " + count);
try {
Thread.sleep(1000);
count++;
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
//创建Cat对象,可以当做线程使用
SimpleThread thread = new SimpleThread();
//启动线程
thread.start();
}
}
- 创建一个类实现Runnable接口, 并重写该接口的run()方法,该run()方法的方法体同样是该线程的线程执行体。
- 创建Runnable实现类的实例, 然后使用Runnable实例创建一个Thread实例,
- 调用Thread实例的start方法开始线程
package SimpleThread;
public class SimpleRunnable {
//创建一个类实现Runnable接口
public static class TaskOne implements Runnable{
static int count = 0;
//重写该接口的run()方法
@Override
public void run() {
while(true) {
count++;
System.out.println("taskOne: " + count);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
//创建一个类实现Runnable接口
public static class TaskTwo implements Runnable{
static int count = 0;
//重写该接口的run()方法
@Override
public void run() {
while(true) {
count++;
System.out.println("taskTwo: " + count);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public static void main(String[] args) {
//创建Runnable实现类的实例
TaskOne taskOne = new TaskOne();
TaskTwo taskTwo = new TaskTwo();
//使用Runnable实例创建Thread实例
Thread t1 = new Thread(taskOne);
Thread t2 = new Thread(taskTwo);
//调用Thread实例的start方法开始线程
t1.start();
t2.start();
}
}
使用Runnable接口
- 优点
- 使用Runnable接口的类还可以继承其他类
- 多个线程可以共享一个target对象
- 缺点
- 编程稍微复杂, 比如要访问当前线程, 则必须使用Thread.currentThread()方法
继承Thread类
- 优点
编写简单, 比如需要访问当前线程,则直接使用this
- 缺点
因为已经继承了Thread类, 则不能继承其他父类