关键词:
Thread(线程类,用于管理线程的创建、开启及相关信息)
Runnable(定义任务的接口)
一、继承Thread类的方法
局限性:
因为继承了Thread类,所以不能再继承其他父类。
流程:
1.创建一个继承于Thread类的子类
2.重写Thread类的run()方法
3.创建Thread子类的对象
4.通过此对象调用start()方法
public class ThreadDemo {
public static void main(String[] args) {
// 创建自定义类的对象
SubThread thread = new SubThread();
// 启动线程对象
thread.start();
}
}
// 继承Thread类, 重写run()方法
class SubThread extends Thread {
/**
* 重写run方法 指定要执行的任务 run方法用于定义该线程要执行的任务
*/
@Override
public void run() {
System.out.println("线程任务");
}
}
为什么重写run()?
因为不是类中所有代码都要被线程执行, 为了区分哪些代码需要被执行, java提供了Thread类中的run()方法用来包含那些被线程执行的代码。
二、Runnable接口
优点:
避免单继承的局限性。
增强了程序的扩展性,降低了程序的耦合性;适合多个相同的程序的代码去处理同一个资源的情况, 把线程与程序的代码, 数据有效分离。
流程:
1.自定义类实现接口
2.重写run()方法
3.创建该类实例
4.创建Thread类的对象
//自定义类实现接口
public class Test implements Runnable {
private int ticket = 78;
// 重写run()方法
@Override
public void run() {
while (ticket > 0) {
synchronized (Test.class) {
if (ticket > 0) {
ticket--;
System.out.println(Thread.currentThread().getName()
+ "正在售票,剩余" + ticket + "张");
}
}
try {
// 休眠
Thread.sleep(1000);
} catch (InterruptedException e) {// InterruptedException当线程在活动之前或活动期间处于正在等待、休眠或占用状态且该线程被中断时,抛出该异常。
e.printStackTrace();
}
}
}
public static void main(String[] args) {
Test ticket = new Test();
// 创建多个Thread类对象开启多线程
Thread t1 = new Thread(ticket, "售票口1:");
Thread t2 = new Thread(ticket, "售票口2:");
Thread t3 = new Thread(ticket, "售票口3:");
t1.start();
t2.start();
t3.start();
}
}