1. 线程分析
方式一:实现 Runnable 接口,最终会调用 target.run()
public class Thread implements Runnable {
private Runnable target;
public Thread(Runnable target) {
init(null, target, "Thread-" + nextThreadNum(), 0);
}
// name 设置线程名称
public Thread(String name) {
init(null, null, name, 0);
}
public Thread(Runnable target, String name) {
init(null, target, name, 0);
}
private void init(ThreadGroup g, Runnable target, String name,
long stackSize, AccessControlContext acc, boolean inheritThreadLocals) {
this.target = target;
}
public void run() {
if (target != null) {
target.run();
}
}
}
方式二:继承 Thread 类
重写 run() ,执行的是重写后的逻辑
2. 匿名内部类方式创建线程
public static void main(String[] args) {
new Thread() {
@Override
public void run() {
System.out.println(this.getName());
}
}.start();
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}).start();
}
2.1 同时使用 Runnable 和 Thread 两种方式实现线程
先内部类, runnable 是作为一个参数
public static void main(String[] args) {
new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Runnable...");
}
}) {
@Override
public void run() {
System.out.println("Thread run");
}
}.start();
}
运行结果:Thread run
执行结果分析:
new Runnable()
只是作为 Thread(Runnable target) {}
构造方法的一个参数,当内部类覆盖 run() 方法后,run() 方法执行的就是内部类重写后的逻辑,不再执行原 Thread 里的 if (target != null) { target.run();}
3. start() vs run()
3.1 start()
- 启动新线程
- 准备工作
- 不能重复调用 start()
Thread thread = new Thread();
thread.start();
thread.start();
重复调用 start() 会抛异常 java.lang.IllegalThreadStateException
at java.lang.Thread.start(Thread.java:708)
源码解析
1.启动新线程
2.加入线程组
3.调用 start0()
public synchronized void start() {
// A zero status value corresponds to state "NEW".
if (threadStatus != 0)
throw new IllegalThreadStateException();
group.add(this);
boolean started = false;
try {
start0();
started = true;
}
}
3.2 run()
public void run() {
if (target != null) {
target.run();
}
}
4. 示例
public static void main(String[] args) {
new Thread(() -> {
while (true) {
log.info("running");
}
}, "t1").start();
new Thread(() -> {
while (true) {
log.info("running");
}
}, "t2").start();
}
网友评论