本例子为实现“监测服务器连接状态”功能的代码片段:
包装数据的类RightAnswer:
//----------------------------------------------------------------------------------------
private class RightAnswer {
public
RightAnswer(
int
rightAnswer
){
this
.
rightAnswer
=
rightAnswer;
}
public
int
getValue
(){
//读取数据
synchronized(
this
){
return
rightAnswer;
}
}
public
void
valueMinus
(){
//数据递减1
synchronized(
this
){
rightAnswer
--;
}
}
public
void
valueAdd
(){
//数据递增1
synchronized(
this
){
rightAnswer
++;
}
}
int
rightAnswer;
}
//----------------------------------------------------------------------------------------=
synchronized( this ){}:同步代码段,花括号内的操作一个时间内只能有一个线程执行,因为这个类的三个方法均用this加锁,这三个方法在同一时间内也只能执行一个,如此保证了对数据操作的有效性
操作这个RightAnswer类对象的两个类,构造方法时传入RightAnswer类对象,实现对象的引用
//-----------------------------------------------------------------------------------------
private class ServerAnswerTimerTask extends TimerTask {
public
ServerAnswerTimerTask(
RightAnswer
rightAnswer
){
this
.
rightAnswer
=
rightAnswer;
}
@Override
public
void
run()
{
rightAnswer
.
valueMinus();
}
RightAnswer
rightAnswer;
}
private class RightAnswerAddThread implements Runnable {
public
RightAnswerAddThread(
RightAnswer
rightAnswer
){
this
.
rightAnswer
=
rightAnswer;
}
@Override
public
void
run()
{
this
.
rightAnswer
.
valueAdd();
}
RightAnswer
rightAnswer;
}
//-----------------------------------------------------------------------------------------
包装数据的类RightAnswer:
//----------------------------------------------------------------------------------------
private class RightAnswer {
}
//----------------------------------------------------------------------------------------=
synchronized( this ){}:同步代码段,花括号内的操作一个时间内只能有一个线程执行,因为这个类的三个方法均用this加锁,这三个方法在同一时间内也只能执行一个,如此保证了对数据操作的有效性
操作这个RightAnswer类对象的两个类,构造方法时传入RightAnswer类对象,实现对象的引用
//-----------------------------------------------------------------------------------------
private class ServerAnswerTimerTask extends TimerTask {
}
private class RightAnswerAddThread implements Runnable {
}
//-----------------------------------------------------------------------------------------