1、 五大状态
线程状态转换
一个线程结束的标志是: run() 方法结束。
一个 机锁 被释放的标志是: synchronized 块或方法结束。
2、线程方法
线程中的几个主要方法的比较:
-
Thread 类的方法: sleep(),yield() 等
-
Object 的方法: wait() 和 notify() 等
由于 sleep() 方法是 Thread 类的方法,因此它不能改变对象的机锁。 所以当在一个 Synchronized 方法中调用 sleep ()时,线程虽然休眠了,但是对象的机锁没有被释放,其他线程仍然无法访问这个对象。而 wait()方法则会在线程休眠的同时释放掉 机锁 ,其他线程可以访问该对象 。
Wait() 方法和 notify() 方法:当一个线程执行到 wait() 方法时( 线程休眠且释放机锁 ),它就进入到一个和 该对象 相关的等待池中,同时失去了对象的机锁。当它被一个 notify()方法唤醒时 ,等待池中的 线程就被放到了锁池中 。该线程从锁池中获得机锁,然后回到 w ait()前的中断现场 。
值得注意的是:线程的在被激活后不一定马上就运行,而是进入到 可运行线程的队列中 。
sleep()和wait()的区别:
- 共同点: 他们都是在多线程的环境下,都可以在程序的调用处阻塞指定的毫秒数,并返回
- 不同点: Thread.sleep(long)可以不在synchronized的块下调用,而且使用Thread.sleep()不会丢失当前线程对任何对象的同步锁(monitor); object.wait(long)必须在synchronized的块下来使用,调用了之后失去对object的monitor, 这样做的好处是它不影响其它的线程对object进行操作。
3、停止线程
停止线程:
不推荐使用JDK提供的 stop()、 destroy()方法。【已废弃】(因为该方法通常容易导致死锁)
推荐线程自己停止下来
建议使用一个标志位进行终止变量 ,当flag=false,则终止线程运行。
//测试线程停止
//1.建议线程正常停止---->利用循环次数,不能死循环
//2.建议使用标志位---->使用一个标志位
//3.不要使用stop或者destroy等过时或者JDK不建议的方法
public class testStop implements Runnable{
//1.设置标志位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag){
System.out.println("Thread is running" + i++);
}
}
//2.设置一个公开的方法停止线程,转换标志位
public void stop(){
this.flag = false;
}
public static void main(String[] args) {
testStop testStop = new testStop();
new Thread(testStop).start();
for(int i = 0; i <1000; i ++){
System.out.println("main"+ i );
if(i == 900){
//调用线程停止方法,转换标志位让线程停止
testStop.stop();
System.out.println("线程该停止了");
}
}
}
}
运行截图:
4、线程休眠
线程休眠
sleep (时间) 指定当前线程阻塞的毫秒数; 1000 ms = 1s
sleep存在异常InterruptedException;
sleep时间达到后线程进入就绪状态;
sleep可以模拟网络延时,倒计时等。
每一个对象都有一个锁,sleep不会释放锁;
1. 模拟网络时延:放大问题的发生性
public class testSleep implements Runnable{
private int ticketNums = 10;
@Override
public void run() {
while(true){
if(ticketNums <= 0){
break;
}
//模拟时延
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
//获得当前执行线程的名字
System.out.println(Thread.currentThread().getName() + "拿到了第" + ticketNums-- + "票");
}
}
public static void main(String[] args) {
testSleep t = new testSleep();
new Thread(t,"凸凸").start();
new Thread(t,"凹凹").start();
new Thread(t,"黄牛").start();
}
}
- 模拟倒计时
import java.text.SimpleDateFormat;
import java.util.Date;
public class testSleep2 {
//模拟倒计时
public static void tenDown() throws InterruptedException {
int num = 10;
while(true){
Thread.sleep(1000);
System.out.println(num--);
if(num <= 0){
break;
}
}
}
public static void main(String[] args) {
//获取系统当前时间
Date startTime = new Date(System.currentTimeMillis());
while(true){
try {
Thread.sleep(1000);
System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));
startTime = new Date(System.currentTimeMillis());//更新当前时间
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
5、线程礼让
线程礼让:Yield() 方法是停止当前线程,让同等优先权的线程运行。如果没有同等优先权的线程,那么 Yield() 方法将不会起作用。
礼让线程,让当前正在执行的线程暂停,但不阻塞
将线程从运行状态转为就绪状态
让cpu重新调度,礼让不一定成功!看CPU心情
public class testYield {
public static void main(String[] args) {
MyYield myYield = new MyYield();
new Thread(myYield,"凸凸").start();
new Thread(myYield,"凹凹").start();
}
}
class MyYield implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "线程开始运行");
Thread.yield();
System.out.println(Thread.currentThread().getName() + "线程结束执行");
}
}
6、Join
Join:join() 方法使当 前线程停下来等待 ,直至另 一个调用join方法的线程 终止。
Join合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞
可以想象成插队
public class testJoin implements Runnable {
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("VIP来了" + i);
}
}
public static void main(String[] args) throws InterruptedException {
testJoin testJoin = new testJoin();
Thread thread = new Thread(testJoin);
thread.start();
for (int i = 0; i < 200; i++) {
if(i == 100){
thread.join();
}
System.out.println("main" + i);
}
}
}
7、线程状态观测
JDk帮助文档
public class testState {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(() ->{
//让线程睡眠5秒
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("///");
});
//观测线程状态
Thread.State state = thread.getState();
System.out.println(state);//NEW
thread.start();
state = thread.getState();
System.out.println(state);//RUNNABLE
while(state != Thread.State.TERMINATED){
Thread.sleep(100);
state = thread.getState();
System.out.println(state);
}
}
}
线程一旦进入死亡状态,就不能再次启动了。
8、线程优先级
Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行。
线程的优先级用数字表示,范围从1~10.
- Thread.MIN_PRIORITY = 1;
- Thread.MAX_PRIORITY = 10;
- Thread.NORM_PRIORITY = 5;
使用以下方式改变或获取优先级
getPriority() . setPriority(int xxx)
优先级的设定在start()调度前
//测试线程优先级
public class testPriority {
public static void main(String[] args) {
//主线程的优先级
System.out.println(Thread.currentThread().getName() + "--->" + Thread.currentThread().getPriority());
MyPriority myPriority = new MyPriority();
Thread t1 = new Thread(myPriority,"t1");
t1.start();
Thread t2 = new Thread(myPriority,"t2");
t2.setPriority(2);
t2.start();
Thread t3 = new Thread(myPriority,"t3");
t3.setPriority(6);
t3.start();
Thread t4 = new Thread(myPriority,"t4");
t4.setPriority(Thread.MAX_PRIORITY);//MAX_PRIORITY=10,MIN_PRIORITY=1
t4.start();
}
}
class MyPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "--->" + Thread.currentThread().getPriority());
}
}
总结:优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用了,这都是看CPU的调度.
9、守护(daemon)线程
线程分为用户线程和守护线程
虚拟机必须确保用户线程执行完毕,如main线程
虚拟机不用等待守护线程执行完毕,如gc线程(垃圾回收等待)、后台记录操作日志、监控内存…
public class testDaemon {
public static void main(String[] args) {
God god = new God();
You you = new You();
Thread thread = new Thread(god);
thread.setDaemon(true);//设置守护线程
thread.start();//守护线程启动
new Thread(you).start();//用户进程启动
}
}
//守护线程
class God implements Runnable{
@Override
public void run() {
while(true){
System.out.println("上帝保佑你!");
}
}
}
//用户线程
class You implements Runnable{
@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("我开心的活着");
}
System.out.println("GoodBye world~~~");
}
}