2022.10.15线程状态观测
线程优先级
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{
守护(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{
线程同步
三大不安全案例
package com.fei.syn;
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;//外部停止方式
同步块
-
同步块:synchronized(Obj){}
-
Obj被称为同步监视器
-
Obj可以是任何对象,但是推荐使用共享资源作为同步监视器
-
同步方法中无需指定同步监视器,因为同步方法的同步监视器就是this,就是这个对象本身,或者是class
-
-
同步监视器的执行过程
-
第一个线程访问,锁定同步监视器,执行其中代码。
-
第二个线程访问,发现同步监视器被锁定,无法访问。
-
-
第二个线程访问,发现同步监视器没有锁,然后锁定并访问。
-
package com.fei.syn;
import java.util.concurrent.CopyOnWriteArrayList;
//测试JUC安全类型的集合
public class TestJUC {
public static void main(String[] args) {
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
for (int i = 0; i < 1000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println(list.size());
}
}

浙公网安备 33010602011771号