文章目录
复习
1.1 进程和线程的区别
1.2 线程创建的方式
1.3 两者创建的区别
2 多线程
2.1多线程的优势-增加了运行的速度
2.2Thread类及常用的方法
2.2.1常用见的构造方法
2.2.2获取当前类的信息
public class Mian {
public static void main(String[] args) {
Thread thread = new Thread(()->{
//获取类名
String className = Mian.class.getName();
System.out.println(className);
//获取线程对象
Thread thread1 = Thread.currentThread();
System.out.println(thread1);
//获取线程名
String name = thread1.getName();
System.out.println(name);
String mName= thread1.getStackTrace()[1].getMethodName();
System.out.println(mName);
},"我是一个线程");
thread.start();
}
}
2.2.3Thread 的⼏个常⻅属性
1 演示后台线程
2 线程是否存活
3 名称
4 线程中断
5 等待⼀个线程 - join()
public class ThreadDemo {
public static void main(String[] args) throws InterruptedException {
Runnable target = () -> {
for (int i = 0; i < 10; i++) {
try {
System.out.println(Thread.currentThread().getName()
+ ": 我还在⼯作!");
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(Thread.currentThread().getName() + ": 我结束了!");
};
Thread thread1 = new Thread(target, "李四");
Thread thread2 = new Thread(target, "王五");
System.out.println("先让李四开始⼯作");
thread1.start();
thread1.join();
System.out.println("李四⼯作结束了,让王五开始⼯作");
thread2.start();
thread2.join();
System.out.println("王五⼯作结束了");
}
}
6 获取当前线程引⽤
2.3.4 线程的状态
线程的状态继承在一个枚举中
public class Main {
public static void main(String[] args) {
for (Thread.State state : Thread.State.values()) {
System.out.println(state);
}
}
}