当前位置: 首页 > news >正文

【Java基础】线程方法

start():启动线程,使线程进入就绪状态。
run():线程执行的代码逻辑,需要重写该方法。

停止线程

void interrupt() 中断线程,让它重新去争抢cpu
如果目标线程长时间等待,则应该使用interrupt方法来中断等待(强制打断,会发生中断异常InterruptedException)

static void yield() 暂停当前正在执行的线程对象,并执行其他线程

不推荐使用JDK提供的stop()、destroy()方法【已废弃】。推荐线程自己停下来,建议使用一个标志位进行终止变量,当flag=false,则终止线程运行。

package com.shan.demo7;
//测试stop
//1.建议线程正常停止————利用次数,不建议死循环
//2.建议使用标志位————设置一个标志位
//3.不要使用stop或者destroy等过时或者JDK不建议使用的方法
public class TestStop implements Runnable{//1. 设置一个标识位private boolean flag=true;@Overridepublic void run() {int i=0;while(flag){System.out.println("run……Thread"+i++);}}//2. 设置一个公开的方法停止线程,转换标志位public void mystop(){this.flag=false;}public static void main(String[] args) throws InterruptedException {TestStop testStop=new TestStop();new Thread(testStop).start();Thread.sleep(20);int i=0;while(true) {//System.out.println("main"+i++);// 主线程没有其他任务时,运行速度很快,// 很容易出现新建的线程启动后,还没有抢到CPU,// 没有运行过,程序就已经停止运行的情况// 我们可以让主线程休眠,或添加其他任务,// 来观看中止线程的效果i++;if (i==10){//调用stop方法切换标志位,让线程停止testStop.mystop();break;}}}
}

线程休眠

static void sleep(long millis) 让当前正在执行的线程休眠的毫秒数;
sleep存在异常InterruptedException;
sleep时间到达后线程进入就绪状态;
sleep可以模拟网络延时、倒计时等。
每一个对象都有一个锁,sleep不会释放锁。

//模拟网络延时:放大问题的发生性
public class TestSleep implements Runnable {private int ticketNums=10;//票数@Overridepublic void run() {while (true){synchronized (this) {if (ticketNums <= 0) break;System.out.println(Thread.currentThread().getName() + "———拿到了第" + ticketNums-- + "张票");}try {Thread.sleep(100);//模拟延时} catch (InterruptedException e) {e.printStackTrace();}}}public static void main(String[] args) {TestSleep ticket=new TestSleep();new Thread(ticket,"小明").start();new Thread(ticket,"笑笑").start();new Thread(ticket,"淘气").start();}
}
//模拟倒计时
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) throws InterruptedException {tenDown();
}
public class TestSleep2 { //打印当前时间public static void main(String[] args) throws InterruptedException {Date startTime=new Date(System.currentTimeMillis());//获取系统当前时间while(true){System.out.println(new SimpleDateFormat("HH:mm:ss").format(startTime));Thread.sleep(1000);//更新系统当前时间startTime=new Date(System.currentTimeMillis());}}
}

线程礼让

**void yield() ** 礼让不一定成功,得看CPU调度情况

public class TestYield{public static void main(String[] args) {MyYield myYield=new MyYield();new Thread(myYield,"a").start();new Thread(myYield,"b").start();}
}
class MyYield implements Runnable{@Overridepublic void run() {System.out.println(Thread.currentThread().getName()+"线程开始执行");Thread.yield();System.out.println(Thread.currentThread().getName()+"线程停止执行");}
}
* 礼让成功: 		 * 礼让不成功:
* a线程开始执行		* a线程开始执行
* b线程开始执行  	    * a线程停止执行
* a线程停止执行	    * b线程开始执行
* b线程停止执行	  	* b线程停止执行

线程强制执行

void join() 等待该线程终止

//测试join方法 (想象为插队)
public class TestJoin implements Runnable {@Overridepublic 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 < 100; i++) {if (i==50)thread.join();//插队System.out.println("main"+i);}}
}

观测线程状态

boolean isAlive() 测试线程是否处于活动状态

public class TestState {public static void main(String[] args) throws InterruptedException {Thread thread=new Thread(()->{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);//RUN//只要线程不终止,就一直输出状态while(state!=Thread.State.TERMINATED){Thread.sleep(1000);state=thread.getState();//更新线程状态System.out.println(state);}//thread.start();//线程死亡后不能再次启动}
}

线程优先级

Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行

线程的优先级用数字表示,范围从1~10。主线程和子线程的默认优先级都是5
优先级高只是先执行的概率高,并不一定先执行;
优先级低只是意味着获得调度的概率低,并不是优先级低就不会被调用

优先级的设定建议在start()调度前

getPriority() 获得当前优先级
setPriority(int pri) 设置线程优先级

Thread.MAX_PRIOROTY=10
Thread.MIN_PRIOROTY=1
Thread.NORM_PRIOROTY=5

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);Thread t2=new Thread(myPriority);Thread t3=new Thread(myPriority);Thread t4=new Thread(myPriority);Thread t5=new Thread(myPriority);//先设置优先级再启动t1.start();t2.setPriority(1);t2.start();t3.setPriority(3);t3.start();t4.setPriority(10);t4.start();t5.setPriority(8);t5.start();}
}
class MyPriority implements Runnable{@Overridepublic void run() {System.out.println(Thread.currentThread().getName()+"----》"+Thread.currentThread().getPriority());}
}

守护线程

线程分为用户线程和守护线程,虚拟机必须确保用户线程执行完毕,不用等待守护线程执行完毕,如:后台记录操作日志,监控内存,垃圾回收等。

void setDaemon(boolean on)
守护线程:后台线程,当所有的前台线程全部结束,即使后台线程没执行完,也立刻结束
需在线程启动前设置

//测试守护线程
//上帝守护你
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);//默认是false,表示是用户线程,普通的线程都是用户线程thread.start();//上帝守护线程开启new Thread(you).start();//你 用户线程启动}
}
//上帝
class God implements Runnable{@Overridepublic void run() {while(true){System.out.println("上帝保佑众生");}}
}
//你
class You implements Runnable{@Overridepublic void run() {for (int i = 0; i < 36500; i++) {System.out.println("开心地活着,第"+i+"天");}System.out.println("Goodbye,world!");}
}

用户线程执行完后,守护线程还运行了一会儿是因为,虚拟机关闭需要一定的时间

http://www.lryc.cn/news/366031.html

相关文章:

  • C++之动态数组
  • 使用 image-combiner 开源项目实现对海报图片的生成
  • 【缓存】框架层常见问题和对策
  • 【FAS】《CN103106397B》
  • 3D按F3为什么显示不出模型?---模大狮模型网
  • C++设计模式——Adapter适配器模式
  • Python文本处理利器:jieba库全解析
  • 【C/C++】C语言如何实现类似C++的智能指针?
  • 九大微服务监控工具详解
  • java aliyun oss上传和下载工具类
  • P7 品牌管理
  • C语言详解(动态内存管理)1
  • 106.网络游戏逆向分析与漏洞攻防-装备系统数据分析-在UI中显示装备与技能信息
  • AWS EMR Serverless
  • Java面试题:Redis持久化问题
  • 【Java】解决Java报错:ClassCastException
  • OpenCV-最小外接圆cv::minEnclosingCircle
  • 大小堆运用巧解数据流的中位数
  • AI能力边界不断扩展,将对国家安全产生深远影响
  • 【UnityShader入门精要学习笔记】第十六章 Unity中的渲染优化技术 (上)
  • GPT-4o:免费且更快的模型
  • docker部署fastdfs
  • 【劲舞团game】
  • Day15—图像爬虫与简单处理
  • Rust基础学习-Rust中的文件操作
  • Activator.CreateInstance 与 Type.InvokeMember的区别
  • Java18+​App端采用uniapp+开发工具 idea hbuilder智能上门家政系统源码,一站式家政服务平台开发家政服务
  • 【MySQL】探索 MySQL 的 GROUP_CONCAT 函数
  • SpringBoot整合RabbitMQ (持续更新中)
  • 瑞鑫RK3588 画中画 OSD 效果展示