zoukankan
html css js c++ java
Java多线程-一个简单的线程,实现挂起和恢复的功能
主程式代码:
public
class
MainApp
{
public
static
void
main(String[] args)
{
try
{
MySprite dog
=
new
MySprite(
"
狗狗
"
);
MySprite cat
=
new
MySprite(
"
喵喵
"
);
MySprite pig
=
new
MySprite(
"
猪猪
"
);
System.out.println(
"
--- start sprites
"
);
dog.start();
cat.start();
pig.start();
Thread.sleep(
500
);
System.out.println(
"
--- suspend dog
"
);
dog.suspend();
System.out.println(
"
--- main thread do something
"
);
Thread.sleep(
500
);
System.out.println(
"
--- resume dog
"
);
dog.resume();
Thread.sleep(
500
);
System.out.println(
"
--- end dog
"
);
dog.stop();
System.out.println(
"
--- main thread do something
"
);
Thread.sleep(
500
);
System.out.println(
"
--- end other sprites
"
);
cat.stop();
pig.stop();
Thread.sleep(
100
);
System.out.println(
"
--- exit programe.
"
);
}
catch
(InterruptedException e)
{
e.printStackTrace();
}
}
}
线程实现
public
class
MySprite
implements
Runnable
{
/**/
/*
* 线程用变量
*/
private
boolean
running
=
false
;
private
boolean
waiting
=
false
;
private
Thread thread;
/**/
/*
* Business 变量
*/
private
String name;
public
MySprite(String name)
{
this
.name
=
name;
this
.thread
=
new
Thread(
this
);
}
/** */
/**
* 启动线程
*/
public
void
start()
{
running
=
true
;
thread.start();
}
/** */
/**
* 挂起线程
*/
public
void
suspend()
{
if
(waiting)
{
//
是挂起状态则直接返回
return
;
}
synchronized
(
this
)
{
this
.waiting
=
true
;
}
}
/** */
/**
* 恢复线程
*/
public
void
resume()
{
if
(
!
waiting)
{
//
没有挂起则直接返回
return
;
}
synchronized
(
this
)
{
this
.waiting
=
false
;
this
.notifyAll();
}
}
/** */
/**
* 停止线程
*/
public
void
stop()
{
if
(
!
running)
{
//
没有运行则直接返回
return
;
}
synchronized
(
this
)
{
running
=
false
;
}
}
public
void
run()
{
for
(;;)
{
try
{
//
线程挂起和退出处理
synchronized
(
this
)
{
if
(
!
running)
{
break
;
}
if
(waiting)
{
this
.wait();
}
}
//
应该做的事情
cry();
//
进入等待状态
Thread.sleep(
50
);
}
catch
(InterruptedException e)
{
e.printStackTrace();
}
}
}
private
void
cry()
{
System.out.println(name
+
"
:woo!
"
);
}
}
查看全文
相关阅读:
1分钟去除word文档编辑限制密码
建行信用卡微信查询
明目地黄丸
发动机启停技术
ORA-12170: TNS: 连接超时
螃蟹放进冰箱冷冻保存前,要注意什么呢?
螃 蟹要蒸多久
总胆固醇偏高的注意措施及治疗方法
codeforces 375D . Tree and Queries 启发式合并 || dfs序+莫队
codeforces 374D. Inna and Sequence 线段树
原文地址:https://www.cnblogs.com/hcfalan/p/1222960.html
最新文章
moviepy应用pyinstaller打包后执行报错AttributeError: module audio/video.fx.all has no attribute fadein、crop
PyQt(Python+Qt)学习随笔:windows下使用pyinstaller将PyQt文件打包成exe可执行文件
windows下使用pyinstaller将多个目录的Python文件打包成exe可执行文件
老猿学5G随笔:5G系统构成
老猿学5G随笔:5G的三大业务场景eMBB、URLLC、mMTC
PyQt(Python+Qt)学习随笔:print标准输出sys.stdout以及stderr重定向QTextBrowser等图形界面对象
在Python实现print标准输出sys.stdout、stderr重定向及捕获的简单办法
PyQt(Python+Qt)学习随笔:MoviePy视频转GIF动图相关方法介绍
[转]2013年小米校园招聘笔试题
[转]2013年完美世界校园招聘笔试题
热门文章
[转]2013年海康威视校园招聘笔试题
[转]Hulu 2013北京地区校招笔试题
[]2013年人人校园招聘笔试题
[转]网易2013校园招聘笔试题集锦
[转]关于数组的几道面试题
[转]程序员面试100题之十六:二叉树中两个节点的最近公共父节点
[转]优酷土豆2012.9.12校园招聘会笔试题
[转]Google2012.9.24校园招聘会笔试题
车上出现这五种状况 可能是被偷车贼盯上了
牢记10个方法,就能让孩子拥有自保的能力!
Copyright © 2011-2022 走看看