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!
"
);
}
}
查看全文
相关阅读:
Linux内核异常处理体系结构详解(一)【转】
一则利用内核漏洞获取root权限的案例【转】
linux tracepoint用法【转】
实现PC视频播放最强画质教程( Potplayer播放器+MADVR插件)【转】
getopt_long函数使用【转】
用Qemu运行/调试arm linux【转】
linux内核input子系统解析【转】
Linux input子系统 io控制字段【转】
Linux设备树语法详解【转】
of_alias_get_id 函数与设备树中aliases节点的关系【转】
原文地址:https://www.cnblogs.com/hcfalan/p/1222960.html
最新文章
WPF程序中的弱事件模式
在C#中实现简单的对象池
Windows 8.1中WinRT的变化(二)——新增功能
Windows 8.1中WinRT的变化(一)——新增控件
使用CallerMemberName简化InotifyPropertyChanged的实现
微软官方的精简版Windows 7——Windows Thin PC
Word 2013双引号的BUG
体验VisualStudio 2013中的内存分析功能
为Chrome多账户添加单独的快捷方式
如何修改WP文章字体格式、字号大小、字体颜色
热门文章
WordPress SMTP发送邮件插件:WP SMTP
如何设置WordPress文章特色图像(Featured Image)
微信公众号推送文图片什么尺寸最佳?(转)
如何修改wordpress的.po和.mo配置文件
PHP需要学习成长路径
微信公号文章排版:微信公众号新增4个新功能
最佳 WordPress 静态缓存插件 WP Super Cache 安装和使用(转)
如何优雅的选择字体(font-family)
一次触摸屏中断调试引发的深入探究【原创】
中断API之setup_irq【转】
Copyright © 2011-2022 走看看