目录
线程创建
1. 继承Thread,重写 run 方法
//1.继承Thread来创建一个线程类
class MyThread extends Thread{
@Override
public void run(){
System.out.println("线程");
}
}
//2.创建 MyThread 的实例
MyThread myThread = new MyThread();
//3.调用 start 方法启动线程
myThread.start();
2. 实现Runnable,重写 run 方法
//1.实现 Runnable 接口
class MyRunnable implements Runnable{
@Override
public void run() {
System.out.println("线程");
}
}
//2.创建 Thread 类实例,调用 Thread 的构造方法, 将Runnable 对象作为 target 参数
Thread t = new Thread (new MyRunnable() );
//3.调用 start 方法
t.start();
3. 继承Thread,使用匿名内部类
//1.使用匿名内部类创建
Thread thread = new Thread(){
@Override
public void run() {
System.out.println("线程");
}
};
//2.调用 start 方法
thread.start();
4. 实现Runnable,使用匿名内部类
//1.使用匿名内部类 Runnable接口 创建
Thread t = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("线程");
}
});
//2.start
t.start();
5. 使用 lambda 表达式(最常用 最方便)
//1.lambda表达式
Thread thread = new Thread(()->{
System.out.println("线程");
});
//2.调用start方法
thread.start();
线程等待 -- join
1. 概念
t . join ( ) ;
在main程序中,出现这个语句会让main线程阻塞等待,
等待t执行完之后 main 才会继续执行。
主要用来控制线程之间的结束顺序。
2. join 的三种方法
public void jion () | 等待线程结束 |
public void jion (long millis) | 等待线程结束,最多等待millis毫秒 |
public void jion (long millis , int nanos) | 同理,但可以更高精度 |
线程休眠
1. 休眠的两种方法
有一点我们要知道,线程的调度是不可控的,所以实际休眠时间是大于参数设置的休眠时间的
public static void sleep(long millis)throws InterruptedException | 休眠当前线程millis毫秒 |
public static void sleep(long millis,int nanos)throws InterruptedException | 同理,更高的精度 |
获取线程实例
public class Demo {
public static void main(String[] args) throws InterruptedException {
Thread thread1 = new Thread(()->{
System.out.println(1);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
Thread thread2 = new Thread(()->{
System.out.println(2);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
System.out.println("OK");
}
}