Java多线程快速入门

1、线程和进程的区别

2、多线程的应用场景

3、多线程的创建方式

(1)继承Thread类,重写run()方法
class ThreadDemo extends Thread {
@Override
public void run() {
System.out.println("这里是子线程");
System.out.println("线程名称:" + this.getName());
System.out.println("线程ID:" + this.getId());
}
} public class JavaThreadDemo01 { public static void main(String[] args) {
System.out.println("这里是主线程");
ThreadDemo threadDemo = new ThreadDemo();
threadDemo.start();
}
}
(2)实现Runnable接口,重写run()方法
class RunnableDemo implements Runnable {

    @Override
public void run() {
System.out.println("这里是子线程");
System.out.println("线程名称:" + Thread.currentThread().getName());
System.out.println("线程ID:" + Thread.currentThread().getId());
}
} public class JavaThreadDemo02 { public static void main(String[] args) {
System.out.println("这里是主线程");
RunnableDemo runnableDemo = new RunnableDemo();
Thread thread = new Thread(runnableDemo);
thread.start();
}
}
(3)使用匿名内部类方式
public class JavaThreadDemo03 {

    public static void main(String[] args) {
System.out.println("主线程");
// 使用实现接口的方式
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("这里是子线程");
System.out.println("线程名称:" + Thread.currentThread().getName());
System.out.println("线程ID:" + Thread.currentThread().getId());
}
});
thread1.start(); // 使用lambda表达式
Thread thread2 = new Thread(() -> {
System.out.println("这里是子线程");
System.out.println("线程名称:" + Thread.currentThread().getName());
System.out.println("线程ID:" + Thread.currentThread().getId());
});
thread2.start();
}
}
(4)使用继承Thread类还是使用实现Runnable接口的方式新建线程好?
(5)启动线程调用start()方法还是run()方法?

4、多线程运行状态

5、判断线程的存活状态

源码地址

04-28 11:05