Java 中实现自定义线程有两种方式,继承Thread 类, 或实现Runable 接口. 查看源码会发现, Thread 也实现了Runnable 接口. 无论那种方式都需要重写run方法, 虽然Runnable 时强制的, Thread 是非必须的。
1. 核心概念
1.1 Thread 与 Runnable 的区别
使用Thread 创建的类不能继承其它父类, 因为java 中一个类只允许继承一个父类。 可独立运行
Runable不能独立运行, 必须依赖于一个Thread.
1.2 Thread的两个方法: start与run
Thead 有两个执行方法: start 和 run. 无论调用哪个方法,都会执行run方法. 区别是:
调用run方法: 和调用普通对象的方法一样, 由当前线程执行
调用start方法: 会新起子线程执行
public static void main(String[] args) {
Thread thread = new Thread("newThread"){
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
};
//thread.run(); // 输出main
thread.start(); // 输出:newThread
}
2. 使用 Runnable 创建异步线程
作为异步线程时,Runnable必须依赖于Thread来执行。
2.1 自定义类方式
public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.printf("%s-%s-%s", LocalDateTime.now(),
Thread.currentThread().getName(), Thread.currentThread().getClass().getName());
}
public static void main(String[] args) {
MyRunnable myRunnable = new MyRunnable();
Thread thread = new Thread();
thread.start();
}
}
2.2 匿名内部类
public static void main(String[] args) {
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.printf("%s-%s-%s", LocalDateTime.now(),
Thread.currentThread().getName(), Thread.currentThread().getClass().getName());
}
};
Thread thread = new Thread(runnable);
thread.start();
}
3. 使用Thread 创建异步线程
3. 1 自定义类
public class MyThread extends Thread {
@Override
public void run() {
System.out.printf("%s-%s-%s", LocalDateTime.now(),
Thread.currentThread().getName(), Thread.currentThread().getClass().getName());
}
public static void main(String[] args) {
MyThread myThread = new MyThread();
myThread.start();
}
}
3.2 匿名内部类
public static void main(String[] args) {
Thread thread = new Thread(){
@Override
public void run() {
System.out.printf("%s-%s-%s", LocalDateTime.now(),
Thread.currentThread().getName(), Thread.currentThread().getClass().getName());
}
};
thread.run();
}
标签:Runnable,Java,自定义,Thread,void,线程,getName,run,public
来源: https://blog.csdn.net/zongf0504/article/details/88924986