Java 中Thread的sleep、join、yield方法解析

1.Thread中sleep方法作用是使当前线程等待,其他线程开始执行,如果有线程锁,sleep不会让出锁

没有加锁代码如下:

public class SynchronizedSleepMethod {public static void main(String[] args) {MoneyMethod moneyMethod = new MoneyMethod();for (int i = 0; i < 10; i++) {Thread t = new Thread(new MyThread4(moneyMethod), "t1" + i);t.start();}for (int i = 0; i < 10; i++) {Thread t = new Thread(new MyThread5(moneyMethod), "t2" + i);t.start();}}}class MyThread4 implements Runnable {MoneyMethod moneyMethod;/*** */public MyThread4(MoneyMethod moneyMethod) {// TODO Auto-generated constructor stubthis.moneyMethod = moneyMethod;}/** (non-Javadoc)* * @see java.lang.Runnable#run()*/@Overridepublic void run() {try {Thread.sleep(1000);moneyMethod.addMoney();} catch (InterruptedException e) {// TODO Auto-generated catch block
            e.printStackTrace();}}}class MyThread5 implements Runnable {MoneyMethod moneyMethod;/*** */public MyThread5(MoneyMethod moneyMethod) {// TODO Auto-generated constructor stubthis.moneyMethod = moneyMethod;}/** (non-Javadoc)* * @see java.lang.Runnable#run()*/@Overridepublic void run() {try {Thread.sleep(1000);moneyMethod.subMoney();} catch (InterruptedException e) {// TODO Auto-generated catch block
            e.printStackTrace();}
//        System.out.println(moneyMethod.money);// TODO Auto-generated method stub
}}class MoneyMethod {int money = 200;public void addMoney() throws InterruptedException {System.out.println(Thread.currentThread().getName() + ":::run:::" + money);money++;}public void subMoney() throws InterruptedException {System.out.println(Thread.currentThread().getName() + ":::run:::" + money);money--;}}

结果如下:

t10:::run:::202
t12:::run:::202
t11:::run:::202
t13:::run:::203
t15:::run:::205
t14:::run:::204
t17:::run:::207
t19:::run:::209
t18:::run:::209
t16:::run:::207
t21:::run:::207
t24:::run:::205
t22:::run:::206
t20:::run:::206
t29:::run:::203
t28:::run:::203
t26:::run:::202
t27:::run:::201
t23:::run:::200
t25:::run:::199

加锁代码如下:

public class SynchronizedSleepMethod {public static void main(String[] args) {MoneyMethod moneyMethod = new MoneyMethod();for (int i = 0; i < 10; i++) {Thread t = new Thread(new MyThread4(moneyMethod), "t1" + i);t.start();}for (int i = 0; i < 10; i++) {Thread t = new Thread(new MyThread5(moneyMethod), "t2" + i);t.start();}}}class MyThread4 implements Runnable {MoneyMethod moneyMethod;/*** */public MyThread4(MoneyMethod moneyMethod) {// TODO Auto-generated constructor stubthis.moneyMethod = moneyMethod;}/** (non-Javadoc)* * @see java.lang.Runnable#run()*/@Overridepublic void run() {try {Thread.sleep(1000);moneyMethod.addMoney();} catch (InterruptedException e) {// TODO Auto-generated catch block
            e.printStackTrace();}}}class MyThread5 implements Runnable {MoneyMethod moneyMethod;/*** */public MyThread5(MoneyMethod moneyMethod) {// TODO Auto-generated constructor stubthis.moneyMethod = moneyMethod;}/** (non-Javadoc)* * @see java.lang.Runnable#run()*/@Overridepublic void run() {try {Thread.sleep(1000);moneyMethod.subMoney();} catch (InterruptedException e) {// TODO Auto-generated catch block
            e.printStackTrace();}
//        System.out.println(moneyMethod.money);// TODO Auto-generated method stub
}}class MoneyMethod {int money = 200;public synchronized void addMoney() throws InterruptedException {money++;System.out.println(Thread.currentThread().getName() + ":::run:::" + money);}public synchronized void subMoney() throws InterruptedException {money--;System.out.println(Thread.currentThread().getName() + ":::run:::" + money);}}

结果如下:

t10:::run:::201
t18:::run:::202
t17:::run:::203
t12:::run:::204
t13:::run:::205
t14:::run:::206
t15:::run:::207
t16:::run:::208
t11:::run:::209
t19:::run:::210
t22:::run:::209
t21:::run:::208
t20:::run:::207
t25:::run:::206
t24:::run:::205
t23:::run:::204
t26:::run:::203
t27:::run:::202
t29:::run:::201
t28:::run:::200

2.Thread中join()方法阻塞调用此方法的线程(calling thread),直到线程t完成,此线程再继续;

没有join()方法代码如下:

public class JoinMethod {public static void main(String[] args) throws InterruptedException {MoneyMethod2 moneyMethod = new MoneyMethod2();for (int i = 0; i < 5; i++) {Thread t = new Thread(new MyThread4(moneyMethod), "t1" + i);t.start();
//            t.join(300);System.out.println(Thread.currentThread().getName() + ":::run:::1"+i);}for (int i = 0; i < 5; i++) {Thread t = new Thread(new MyThread5(moneyMethod), "t2" + i);t.start();
//            t.join(300);System.out.println(Thread.currentThread().getName() + ":::run:::2"+i);}System.out.println(Thread.currentThread().getName() + ":::finish:::");}
}class MyThread4 implements Runnable {MoneyMethod2 moneyMethod;/*** */public MyThread4(MoneyMethod2 moneyMethod) {// TODO Auto-generated constructor stubthis.moneyMethod = moneyMethod;}/** (non-Javadoc)* * @see java.lang.Runnable#run()*/@Overridepublic void run() {try {Thread.sleep(2000);moneyMethod.addMoney();} catch (InterruptedException e) {// TODO Auto-generated catch block
            e.printStackTrace();}}}class MyThread5 implements Runnable {MoneyMethod2 moneyMethod;/*** */public MyThread5(MoneyMethod2 moneyMethod) {// TODO Auto-generated constructor stubthis.moneyMethod = moneyMethod;}/** (non-Javadoc)* * @see java.lang.Runnable#run()*/@Overridepublic void run() {try {Thread.sleep(2000);moneyMethod.subMoney();} catch (InterruptedException e) {// TODO Auto-generated catch block
            e.printStackTrace();}
//        System.out.println(moneyMethod.money);// TODO Auto-generated method stub
}}class MoneyMethod2 {int money = 200;public void addMoney() throws InterruptedException {money++;System.out.println(Thread.currentThread().getName() + ":::add:::" + money);}public void subMoney() throws InterruptedException {money--;System.out.println(Thread.currentThread().getName() + ":::sub:::" + money);}}

结果:主线程会提前走掉,然后子线程执行

main:::run:::10
main:::run:::11
main:::run:::12
main:::run:::13
main:::run:::14
main:::run:::20
main:::run:::21
main:::run:::22
main:::run:::23
main:::run:::24
main:::finish:::
t10:::add:::201
t12:::add:::202
t11:::add:::203
t13:::add:::204
t14:::add:::205
t21:::sub:::203
t20:::sub:::203
t24:::sub:::201
t22:::sub:::200
t23:::sub:::201

添加了join后,join的等待时间>线程执行时间,代码如下:

public class JoinMethod {public static void main(String[] args) throws InterruptedException {MoneyMethod2 moneyMethod = new MoneyMethod2();for (int i = 0; i < 5; i++) {Thread t = new Thread(new MyThread4(moneyMethod), "t1" + i);t.start();t.join(3000);System.out.println(Thread.currentThread().getName() + ":::run:::1"+i);}for (int i = 0; i < 5; i++) {Thread t = new Thread(new MyThread5(moneyMethod), "t2" + i);t.start();t.join(3000);System.out.println(Thread.currentThread().getName() + ":::run:::2"+i);}System.out.println(Thread.currentThread().getName() + ":::finish:::");}
}class MyThread4 implements Runnable {MoneyMethod2 moneyMethod;/*** */public MyThread4(MoneyMethod2 moneyMethod) {// TODO Auto-generated constructor stubthis.moneyMethod = moneyMethod;}/** (non-Javadoc)* * @see java.lang.Runnable#run()*/@Overridepublic void run() {try {Thread.sleep(2000);moneyMethod.addMoney();} catch (InterruptedException e) {// TODO Auto-generated catch block
            e.printStackTrace();}}}class MyThread5 implements Runnable {MoneyMethod2 moneyMethod;/*** */public MyThread5(MoneyMethod2 moneyMethod) {// TODO Auto-generated constructor stubthis.moneyMethod = moneyMethod;}/** (non-Javadoc)* * @see java.lang.Runnable#run()*/@Overridepublic void run() {try {Thread.sleep(2000);moneyMethod.subMoney();} catch (InterruptedException e) {// TODO Auto-generated catch block
            e.printStackTrace();}
//        System.out.println(moneyMethod.money);// TODO Auto-generated method stub
}}class MoneyMethod2 {int money = 200;public void addMoney() throws InterruptedException {money++;System.out.println(Thread.currentThread().getName() + ":::add:::" + money);}public void subMoney() throws InterruptedException {money--;System.out.println(Thread.currentThread().getName() + ":::sub:::" + money);}}

结果如下:

t10:::add:::201
main:::run:::10
t11:::add:::202
main:::run:::11
t12:::add:::203
main:::run:::12
t13:::add:::204
main:::run:::13
t14:::add:::205
main:::run:::14
t20:::sub:::204
main:::run:::20
t21:::sub:::203
main:::run:::21
t22:::sub:::202
main:::run:::22
t23:::sub:::201
main:::run:::23
t24:::sub:::200
main:::run:::24
main:::finish:::

加入join方法后,线程执行时间>join的等待时间时,代码如下:

public class JoinMethod {public static void main(String[] args) throws InterruptedException {MoneyMethod2 moneyMethod = new MoneyMethod2();for (int i = 0; i < 5; i++) {Thread t = new Thread(new MyThread4(moneyMethod), "t1" + i);t.start();t.join(300);System.out.println(Thread.currentThread().getName() + ":::run:::1"+i);}for (int i = 0; i < 5; i++) {Thread t = new Thread(new MyThread5(moneyMethod), "t2" + i);t.start();t.join(300);System.out.println(Thread.currentThread().getName() + ":::run:::2"+i);}System.out.println(Thread.currentThread().getName() + ":::finish:::");}
}class MyThread4 implements Runnable {MoneyMethod2 moneyMethod;/*** */public MyThread4(MoneyMethod2 moneyMethod) {// TODO Auto-generated constructor stubthis.moneyMethod = moneyMethod;}/** (non-Javadoc)* * @see java.lang.Runnable#run()*/@Overridepublic void run() {try {Thread.sleep(2000);moneyMethod.addMoney();} catch (InterruptedException e) {// TODO Auto-generated catch block
            e.printStackTrace();}}}class MyThread5 implements Runnable {MoneyMethod2 moneyMethod;/*** */public MyThread5(MoneyMethod2 moneyMethod) {// TODO Auto-generated constructor stubthis.moneyMethod = moneyMethod;}/** (non-Javadoc)* * @see java.lang.Runnable#run()*/@Overridepublic void run() {try {Thread.sleep(2000);moneyMethod.subMoney();} catch (InterruptedException e) {// TODO Auto-generated catch block
            e.printStackTrace();}
//        System.out.println(moneyMethod.money);// TODO Auto-generated method stub
}}class MoneyMethod2 {int money = 200;public void addMoney() throws InterruptedException {money++;System.out.println(Thread.currentThread().getName() + ":::add:::" + money);}public void subMoney() throws InterruptedException {money--;System.out.println(Thread.currentThread().getName() + ":::sub:::" + money);}}

结果如下:

main:::run:::10
main:::run:::11
main:::run:::12
main:::run:::13
main:::run:::14
main:::run:::20
t10:::add:::201
main:::run:::21
t11:::add:::202
main:::run:::22
t12:::add:::203
main:::run:::23
t13:::add:::204
main:::run:::24
main:::finish:::
t14:::add:::205
t20:::sub:::204
t21:::sub:::203
t22:::sub:::202
t23:::sub:::201
t24:::sub:::200

在以上代码中可以发现,在加入join()方法后主线程还是会提前走,但是所有子线程会按照执行顺序执行

3.Thread.yield()方法作用是:暂停当前正在执行的线程对象,并执行其他线程,但是有一定几率线程调度程序会将执行被暂停的线程

 

转载于:https://www.cnblogs.com/vstarcui/p/9841769.html

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/352398.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

MySQL与PostgreSQL:该选择哪个开源数据库?哪一个更好?

Naresh Kumar是一位软件工程师与热情的博主&#xff0c;对编程与新事物充满了激情和兴趣。近日&#xff0c;Naresh撰写了一篇博文&#xff0c;对开源世界最常见的两种数据库MySQL与PostgreSQL的特点进行了详尽的分析和比对。 如果打算为项目选择一款免费、开源的数据库&#x…

jquery select change事件_jQuery实现省市联动效果

<!DOCTYPE html> <html><head><meta charset"UTF-8"><title></title></head><body><select name"province"id"province"><option >请选择</option></select><selec…

MATLAB上的GPU加速计算——学习笔记

MATLAB目前只支持Nvidia的显卡。如果你的显卡是AMD的或者是Intel的&#xff0c;就得考虑另寻它路了。 MATLAB可谓工程计算中的神器&#xff0c;一方面它自带丰富的函数库&#xff0c;另一方面它所有的数据都是内建的矩阵类型&#xff0c;最后画图也方便&#xff0c;因此解决一…

java中代码块的概述_Java代码质量工具–概述

java中代码块的概述最近&#xff0c;我有机会在本地IT社区聚会上介绍了该主题。 这是基本演示&#xff1a; Java代码质量工具 以及更有意义的思维导图&#xff1a; 但是&#xff0c;我认为我需要更深入地探讨这一主题。 此博客文章应该像是在此方向上进行进一步调查的起点。 …

js原型、原型链、作用链、闭包全解

https://www.2cto.com/kf/201711/698876.html 【对象、变量】 一个对象就是一个类&#xff0c;可以理解为一个物体的标准化定义。它不是一个具体的实物&#xff0c;只是一个标准。而通过对象实例化得到的变量就是一个独立的实物。比如通过一个对象定义了“人”&#xff0c;通过…

Mysql 简介

一 简介&#xff1a;MySQL是最流行的开放源码SQL数据库管理系统&#xff0c;它是由MySQL AB公司开发、发布并支持的。MySQL AB是由多名MySQL开发人创办的一家商业公司。它是一家第二代开放源码公司&#xff0c;结合了开放源码价值取向、方法和成功的商业模型。 1.MySQL是一种数…

python高阶函数闭包装饰器_5.初识python装饰器 高阶函数+闭包+函数嵌套=装饰器...

一.什么是装饰器&#xff1f; 实际上装饰器就是个函数&#xff0c;这个函数可以为其他函数提供附加的功能。 装饰器在给其他函数添加功能时&#xff0c;不会修改原函数的源代码&#xff0c;不会修改原函数的调用方式。 高阶函数&#xff0b;函数嵌套&#xff0b;闭包 &#xff…

Matlab 画图字体,字号的设定,图片大小和比例

figure_FontSize12; set(get(gca,XLabel),FontSize,figure_FontSize,Vertical,top); set(get(gca,YLabel),FontSize,figure_FontSize,Vertical,middle); set(findobj(FontSize,12),FontSize,figure_FontSize); %这4句是将字体大小改为8号字&#xff0c;在小图里很清晰 %set(gcf…

使用Speedment和Spring创建REST API

随着Spring Boot的第4版发布&#xff0c;为Web开发企业应用程序变得非常容易。 代表开发人员仍然需要大量时间的事情是&#xff0c;例如在Hibernate中对现有数据库进行建模&#xff0c;以获取数据的面向对象的视图。 在本教程中&#xff0c;我们将探索如何与开源一起使用开源工…

Phpstorm界面不停的indexing,不停的闪烁

选择 File->Invalidate Caches / Restart...->Invalidate and Restart&#xff0c;就行了&#xff01;转载于:https://www.cnblogs.com/php-no-2/p/9848606.html

Matlab 集群计算平台搭建

家庭云服务器高阶应用&#xff1a;通过Matlab分布式计算来演示所谓的“家庭云计算”&#xff08;非云储存&#xff09;(转)Matlab是强大的计算软件&#xff0c;这不需要过多介绍了&#xff0c;大到航天航空领域&#xff0c;小到计算方程式&#xff0c;Matlab无处不在。 像是这种…

c打印无符号整数_C语言基础知识:printf的输出格式,C/C++语言编程讲解

C语言基础知识&#xff1a;printf的输出格式printf()函数是格式输出函数&#xff0c;请求printf()打印变量的指令取决与变量的类型&#xff0e;例如&#xff0c;在打印整数是使用&#xff05;d符号&#xff0c;在打印字符是用&#xff05;c 符号&#xff0e;这些符号被称为转换…

CGI简介

原始的HTML語言是設計用來展現靜態的資料&#xff0c;它讓人使用一種簡單的語法展現出豐富的多媒體資料&#xff0c;就像廣告看板一樣。 由於WWW具有相當大的商業用途&#xff0c;因此推出後大受歡迎。可是單純的靜態展示好像缺少了什麼? 如果使用者需要的資料具有時效性&…

数据分析——pyecharts

导入类库 1 from pyecharts import Pie, Bar, Gauge, EffectScatter, WordCloud, Map, Grid, Line, Timeline 2 import random make_point&#xff1a;标注&#xff0c;类似于matplotlib的text is_stack&#xff1a;堆叠&#xff0c;将同一图表中的不同图像堆叠显示 is_label_s…

第三方软件要使用QQ邮箱进行发邮件相关设置

1、要在QQ邮箱的设置界面进行相关设置。 开启相应的服务器&#xff0c;然后获得相应的授权密码即可。 相关参考&#xff1a; http://service.mail.qq.com/cgi-bin/help?subtype1&&id28&&no1001256 2、对相应的服务器和接口进行设置 相关参考&#xff1a;…

CGI相关介绍

一、CGI 简介CGI 是 Common Gateway Interface 的 简 称 。 其 主 要 的 功 能 是 在WWW 环 境 下 &#xff0c; 藉 由 从 客 户 端 传 递 一 些 讯 息 给 WWW Server &#xff0c; 再由 WWW Server 去 启 动 所 指 定 的 程 式 码 来 完 成 特 定 的 工 作 。所 以 更 明 确 的…

mapreduce 聚合_MapReduce:处理数据密集型文本处理–局部聚合第二部分

mapreduce 聚合这篇文章继续进行有关使用MapReduce进行数据密集型处理的书中实现算法的系列文章。 第一部分可以在这里找到。 在上一篇文章中&#xff0c;我们讨论了使用本地聚合技术来减少通过网络进行混洗和传输的数据量的方法。 减少传输的数据量是提高MapReduce作业效率的主…

最常出现的字符串 Most Common Word

2018-10-26 00:32:05 问题描述&#xff1a; 问题求解&#xff1a; 方法一、Trie 最长出现的字符串&#xff0c;最容易想到的解法就是Trie树了&#xff0c;于是首先使用Trie树进行了实现&#xff0c;代码量有点大&#xff0c;当然了是可以A掉的&#xff0c;只是对于这种Easy的题…

docker启动odoo提示module没有安装_Ubuntu20.04通过docker安装微信

到目前为止&#xff0c;在ubuntu20.04上使用wechat最简单的方式不是wine&#xff0c;而是用docker。今天就传授大家一个一定可以使用的docker安装的wine版本。首先&#xff0c;安装一下docker&#xff1a;sudo apt install docker.io sudo systemctl enable --now dockersudo s…

mysql如何在一个表中插入数据的同时,更新另一个表的数据?

三种方案,你看看哪个比较适合你1,适用于学生: 写两个方法,一个新增一个更新,在新增完了以后马上去查询一下,按主键倒叙排列,取到最新插入的id,前提主键是自增的且不是uuid,然后把查到的主键返回出去作为形参让更新方法接收到,然后更新即可.2,适用于ssh框架: 写两个事务,事务的传…