1 /******************************************************************************* 2 * Copyright 2011 See AUTHORS file. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 ******************************************************************************/ 16 17 package com.badlogic.gdx.utils; 18 19 /** A pausable thread. The runnable must not execute an inifite loop but should return control to the thread as often as possible 20 * so that the thread can actually pause. 21 * 22 * @author mzechner */ 23 public class PauseableThread extends Thread { 24 final Runnable runnable; 25 boolean paused = false; 26 boolean exit = false; 27 28 /** Constructs a new thread setting the runnable which will be called repeatedly in a loop. 29 * 30 * @param runnable the runnable. */ PauseableThread(Runnable runnable)31 public PauseableThread (Runnable runnable) { 32 this.runnable = runnable; 33 } 34 run()35 public void run () { 36 while (true) { 37 synchronized (this) { 38 try { 39 while (paused) 40 wait(); 41 } catch (InterruptedException e) { 42 e.printStackTrace(); 43 } 44 } 45 46 if (exit) return; 47 48 runnable.run(); 49 } 50 } 51 52 /** Pauses the thread. This call is non-blocking */ onPause()53 public void onPause () { 54 paused = true; 55 } 56 57 /** Resumes the thread. This call is non-blocking */ onResume()58 public void onResume () { 59 synchronized (this) { 60 paused = false; 61 this.notifyAll(); 62 } 63 } 64 65 /** @return whether this thread is paused or not */ isPaused()66 public boolean isPaused () { 67 return paused; 68 } 69 70 /** Stops this thread */ stopThread()71 public void stopThread () { 72 exit = true; 73 if (paused) onResume(); 74 } 75 } 76