我有2 Activty:A和B 第(一)創建並啓動3個線程。機器人 - 暫停運行的線程,而另一項活動是在屏幕
當用戶插入第二個活動(B),我需要所有的線程將被暫停,直到用戶迴歸A活性。
我試着用的onPause()和的onResume()來做到這一點,但它似乎不是很好,也沒有工作:(在活動)
@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;
}
}
}
編輯:一個run方法的建議後,解決方案如下:
@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();
}
}
}
什麼樣的對象是Const.shop?什麼是等待和notifyAll方法看起來像? – Tenfour04
Const.shop來自Object類型。該方法是對象的方法 – user1932595