我有 2 个活动:A 和 B。第一个 (A) 创建并启动 3 个线程。
当用户插入第二个活动(B)时,我需要暂停所有线程,直到用户返回到 A 活动。
我尝试用 onPause() 和 onResume() 来做,但它似乎不好,也不起作用:(在活动 a)
@Override
public void onPause()
{
Const.isWainting = true;
super.onPause();
try {
synchronized(Const.shop){
Const.shop.wait();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Override
public void onResume()
{
super.onResume();
if(Const.isWainting == true){
synchronized(Const.shop){
Const.shop.notifyAll();
Const.isWainting = false;
}
}
}
编辑:以下建议的解决方案之后的运行方法之一:
@Override
public void run()
{
while (true)
{
if (this.isInterrupted() && Const.isWainting){
synchronized (Const.shop) {
try {
Const.shop.wait();
Const.isWainting = false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
for(int i=0; i<Const.MAX_FOOD ; i++){
if(foodArr[i].getStatus() != Const.NOT_ACTIVE){
//move the food one step
foodArr[i].move();
if(foodArr[i].getY() > Const.screenHeight){
foodArr[i].setStatus(Const.NOT_ACTIVE);
}
gameView.postInvalidate();
}
}
if (isInterrupted() && Const.isWainting){
synchronized (Const.shop) {
try {
Const.shop.wait();
Const.isWainting = false;
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
try
{
FoodThread.sleep(5);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
我知道线程不会停止,因为食物继续下降,即使一个循环中的“移动”也只有一个像素 - >所有食物都从屏幕上消失或移动到很多地方......
请帮忙,非常感谢!
编辑2: 活动:
@Override
public void onPause()
{
super.onPause();
Const.isWainting = true;
this.threadAnimal.interrupt();
this.threadFood.interrupt();
this.threadMoney.interrupt();
}
@Override
public void onResume()
{
super.onResume();
Const.isWainting = false;
if(Const.isWainting == true){
synchronized(Const.shop){
Const.shop.notifyAll();
}
}
}
线程之一:
@Override
public void run()
{
while (true)
{
if (this.isInterrupted() && Const.isWainting){
synchronized (Const.shop) {
try {
Const.shop.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
for(int i=0; i<Const.MAX_FOOD ; i++){
if(foodArr[i].getStatus() != Const.NOT_ACTIVE){
foodArr[i].move();
if(foodArr[i].getY() > Const.screenHeight){
foodArr[i].setStatus(Const.NOT_ACTIVE);
}
gameView.postInvalidate();
}
}
if (isInterrupted() && Const.isWainting){
synchronized (Const.shop) {
try {
Const.shop.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
try
{
FoodThread.sleep(5);
}
catch (InterruptedException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}