一. 线程的生命周期
二.线程的实例化
(1) 继承Thread类,重写其中的run
注意:
需要调用start方法,使线程启动
start方法可以开启一个新的线程来执行run中的逻辑
如果直接调用run方法,不会开启一个新的线程
public static voidmain(String[] args) {
MyThread mt= newMyThread();
mt.start();
}static class MyThread extendsThread {
@Overridepublic voidrun() {for (int i = 0; i < 10; i++) {
System.out.println("子线程中的逻辑:" +i);
}
}
}
(2)通过runnable接口
public static voidmain(String[] args) {
Runnable r1= () ->{for (int i = 0; i < 10; i++) {
System.out.println("线程2的逻辑" +);
}
};
Thread t2= newThread(r1);
t2.start();
}
三. 线程的命名
(1).setName 命名
public static voidmain(String[] args) {
Runnable r1= () ->{for (int i = 0; i < 10; i++) {
System.out.println("线程2的逻辑" +);
}
};
Thread t2= newThread(r1);
t2.start();
t2.setName("custom");//线程的命名
}
(2)实例化一个线程对象的同事,通过构造方法对线程进行命名
Thread t = new Thread(()->{//线程的任务
},"custom");
(3)
static class MyThread extendsThread {
@Overridepublic voidrun() {for (int i = 0; i < 10; i++) {
System.out.println("子线程中的逻辑:" +i);this.setName("custom");
}
}
}
四. 线程的休眠
1.thread.sleep /ms
2.会抛出异常,需要捕获异常
3.运行态变成阻塞态
class MyThread2 extendsThread{publicMyThread2() {
}publicMyThread2(String name) {this.setName(name);
}
@Overridepublic voidrun() {for (int i = 0; i < 10; i++) {
System.out.println(i);try{//sleep会引发异常,需要处理引发的异常
Thread.sleep(1000);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}
五. 线程的优先级和礼让
线程的礼让: 让当前的运行态的线程释放自己的CPU资源,由运行态变成就绪态
public static voidmain(String[] args) {
Runnable r1= () ->{for (int i = 0; i < 10; i++) {
System.out.println("线程2的逻辑" +i);if (i == 3) Thread.yield();//线程礼让
}
};
Thread t2= new Thread(r1,"Thread-1");
t2.setPriority(10);//设置优先级
t2.start();
}
六. 临界资源
进程的资源不共享,线程的资源共享。
解决办法:
1.同步代码段
对象锁:synchronized(“”)
类锁:synchronized(类名字.class)
2.同步方法
3.同步锁
七. 死锁
死锁解决方法:
wait 等待,是object的一个方法,当前的线程释放自己的锁标记,并且让出cpu资源,使得当前的线程进入等待队列中
Notify 通知,是object类中的一个方法,唤醒等待队列中的一个进程,使这个线程进入锁池。 唤醒的线程由CPU决定
notifyAll 是object的一个方法,唤醒等待队列中的所有线程,并使这些线程进入锁池