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!
"
);
}
}
查看全文
相关阅读:
java中4种修饰符访问权限的区别
Java中List的排序方法
Hibernate事务
@Component、@Service、@Constroller
MySQL查看一个表的创建文本以及删除表某列的索引
深入Session2
Tomcat容器的Session管理
深入Session
使用spring mvc或者resteasy构建restful服务
Spring MVC学习回顾
原文地址:https://www.cnblogs.com/hcfalan/p/1222960.html
最新文章
NSTimer 详细设置
UVA 1160
总结Spring、Hibernate、Struts2官网下载jar文件
[置顶] 我的GB28181标准开发里程碑——基于eXosip的IPC端与SPVMN注册成功
C# RSA在服务上使用出现拒绝方法错误的解决方法
.NET世界各成员之间的关系
正确的lnamp支持SSI的方法!即支持SHTML和include调用!
django在视图中使用模板
数据仓库维度模型粒度提升情况浅析
POJ 1947
热门文章
数据库中表散列之杂谈
游戏系统开发笔记(六)——对象系统设计
jsp验证表单后再提交
小车问题
Embedded Linux Primer----嵌入式Linux基础教程--2.4节--嵌入式Linux发行版
HttpServletResponse输出的中文乱码
呈现报表时出现错误 索引超出范围
Eclipse修改已存在的SVN地址
无法打开物理文件“E:DatabaseVRVIES6841-FZ01-GlobalVRVEIS.mdf”。操作系统错误 5:“5(拒绝访问。)”
spring中@Scope作用域的注解
Copyright © 2011-2022 走看看