在我的android程序中,一个Activity调用一个新的表面视图类,然后又调用一个新的线程类。我希望能够从activity的onPause和onResume方法将值传递给线程类,因此我可以暂停并恢复该线程。我知道传递这些数据的唯一方法是创建一个新实例,它只会创建一个不同的线程。如何在不创建新线程实例的情况下解决这个问题?
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new GameSurface(this));
}
@Override
protected void onResume() {
super.onResume();
//Would like to pass this value
int state = 1;
}
@Override
protected void onPause() {
super.onPause();
//Would like to pass this value
int state = 2;
}
答案 0 :(得分:5)
关于并发的一点背景
并发传递值很容易。查看AtomicInteger
数据类型(更多信息here)。原子性也意味着All or nothing
。此数据类型不一定在线程或处理器之间发送数据(就像使用mpi
一样),但它只是在共享内存上共享数据。
但什么是原子行动?....
原子操作是一种作为单个工作单元执行的操作,不会受到其他操作的干扰。
在Java中,语言规范保证读取或写入变量是原子的(除非变量的类型为long或double)。如果它们被声明为volatile,那么long和double只是原子的......
信用(Lars Vogel的Java Concurrency / Multithreading - Tutorial)
我强烈建议您阅读本文,其中涵盖了atomicity
,thread pools
,deadlocks
和the "volatile" and "synchronized" keyword
等所有内容。
开始上课 这将执行一个新线程(它也可以称为我们的Main Thread
)。
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author Michael Jones
* @description Main Thread
*/
public class start {
private AtomicInteger state;
private Thread p;
private Thread r;
/**
* constructor
* initialize the declared threads
*/
public start(){
//initialize the state
this.state = new AtomicInteger(0);
//initialize the threads r and p
this.r = new Thread(new action("resume", state));
this.p = new Thread(new action("pause", state));
} //close constructor
/**
* Start the threads
* @throws InterruptedException
*/
public void startThreads() throws InterruptedException{
if(!this.r.isAlive()){
r.start(); //start r
}
if(!this.p.isAlive()){
Thread.sleep(1000); //wait a little (wait for r to update)...
p.start(); //start p
}
} //close startThreads
/**
* This method starts the main thread
* @param args
*/
public static void main(String[] args) {
//call the constructor of this class
start s = new start();
//try the code
try {
s.startThreads();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} //start the threads
} //close main
} //close class start
因为整数是原子的,你也可以使用main method
在开始类中的System.out.println("[run start] current state is... "+state.intValue());
以外的任何地方检索它。(如果你希望从main method
中检索它,你必须设置一个Setter / Getter,就像我在 Action Class 中所做的那样)
动作类 这是我们的主题(它也可以称为我们的Slave Thread
)。
import java.lang.Thread.State;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author Michael Jones
* @description Slave Thread
*/
public class action implements Runnable {
private String event = "";
private AtomicInteger state;
/**
* The constructor (this represents the current instance of a thread).
*
* @param event
* @param state
*/
public action(String event, AtomicInteger state) {
this.event = event; // update this instance of event
this.state = state; // update this instance of state
} // constructor
/**
* This method will be called after YourThreadName.Start();
*/
@Override
public void run() {
if (this.event == "resume") {
this.OnResume(); // call resume
} else {
this.OnPause(); // call pause
}
} // close Runnable run() method
/**
* The resume function Use the auto lock from synchronized
*/
public synchronized void OnResume() {
System.out.println("[OnResume] The state was.." + this.getAtomicState()
+ " // Thread: " + Thread.currentThread().getId());
this.setAtomicState(2); // change the state
System.out.println("[OnResume] The state is.." + this.getAtomicState()
+ " // Thread: " + Thread.currentThread().getId());
} // close function
/**
* The pause function Use the auto lock from synchronized
*/
public synchronized void OnPause() {
System.out.println("[OnPause] The state was.." + this.getAtomicState()
+ " // Thread: " + Thread.currentThread().getId());
this.setAtomicState(1); // change the state
System.out.println("[OnPause] The state is.." + this.getAtomicState()
+ " // Thread: " + Thread.currentThread().getId());
} // close function
/**
* Get the atomic integer from memory
*
* @return Integer
*/
private Integer getAtomicState() {
return state.intValue();
}// close function
/**
* Update or Create a new atomic integer
*
* @param value
*/
private void setAtomicState(Integer value) {
if (this.state == null) {
state = new AtomicInteger(value);
} else
state.set(value);
} // close function
} // close the class
控制台输出
[OnResume] The state was..0 // Thread: 9
[OnResume] The state is..2 // Thread: 9
[OnPause] The state was..2 // Thread: 10
[OnPause] The state is..1 // Thread: 10
正如您所看到的,AtomicInteger state
正在线程r
和p
之间的内存中共享。
解决方案和要寻找的事情......
进行并发时,您唯一需要注意的是Race Conditions
/ Deadlocks
/ Livelocks
。有些RaceConditions
出现是因为Threads
是按随机顺序创建的(并且大多数程序员都在顺序排列的思维集中思考)。
我有一行Thread.sleep(1000);
,以便我的Main Thread
为从属线程r
提供一点时间来更新state
(在允许p
运行之前),由于线程的随机顺序。
1)保持对线程的引用并使用方法传递值。 Credit(SJuan76,2012)
在我发布的解决方案中,我将Main Thread
(又名class start
)作为我的主要沟通者,以跟踪我的奴隶使用的Atomic Integer
(aka {{1 }})。我的主要线程也是class action
updating
我的奴隶上的memory buffer
(内存缓冲区的更新发生在应用程序的后台,由{{处理} 1}}类)。
答案 1 :(得分:4)
1)保持对线程的引用并使用方法传递值。
2)在创建线程期间,向它传递一个与Activity共享的对象。将值传递给对象,让线程定期检查它,直到找到值。
答案 2 :(得分:2)
我使用我命名为Share Class
的引用类。它具有volatile
类型的变量。
volatile 用于表示将修改变量的值 通过不同的线程。
public class Share {
public static volatile type M_shared;
}
要更改此变量,您应该锁定它并在更改值后释放锁定。您可以使用Share.M_shared
进行读写。