线程状态观测
线程优先级
package com.fei.stata;
public class TestPriority extends Thread{
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
Mypriority mypriority = new Mypriority();
Thread t1 = new Thread(mypriority);
Thread t2 = new Thread(mypriority);
Thread t3 = new Thread(mypriority);
Thread t4 = new Thread(mypriority);
Thread t5 = new Thread(mypriority);
Thread t6 = new Thread(mypriority);
//先设置优先级在启动
t1.start();
t2.setPriority(5);
t2.start();
t3.setPriority(Thread.MAX_PRIORITY);
t3.start();
t4.setPriority(9);
t4.start();
t5.setPriority(4);
t5.start();
t6.setPriority(6);
t6.start();
}
}
class Mypriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
}
}
守护(daemon)线程
-
线程分为用户线程和守护线程
-
虚拟机必须确保用户线程执行完毕
-
虚拟机不用等待守护线程执行完毕
-
如,后台记录操作日志,监控内存,垃圾回收等待
package com.fei.stata;
public class TestDaemon {
public static void main(String[] args) {
You you = new You();
God god = new God();
Thread thread = new Thread(god);
thread.setDaemon(true);//默认是False表示是用户线程,正常的线程都是用户线程
thread.start();//上帝守护线程启动
new Thread(you).start();//you 你用户线程启动
}
}
//上帝
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");
}
}
线程同步
三大不安全案例
package com.fei.syn;标签:15,Thread,void,start,线程,new,2022.10,public From: https://www.cnblogs.com/Paytonfei/p/16795412.html
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket buyTicket = new BuyTicket();
new Thread(buyTicket,"晋儒").start();
new Thread(buyTicket,"小宪").start();
new Thread(buyTicket,"海朋").start();
}
}
class BuyTicket implements Runnable{
private int ticketNums = 10;
boolean flag = true;//外部停止方式
@Override
public void run() {
//买票
while (flag){
try {
buy();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
}
//synchronized:同步方法,上锁只允许一个线程执行,其他线程阻塞
private synchronized void buy() throws InterruptedException {
//判断是否有票
if (ticketNums<=0){
flag = false;
return;
}
Thread.sleep(100);
//买票
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
}