我有一个与以下链接相关的问题:What's the difference between Thread start() and Runnable run()
在这个问题中,我看到一个人创建可运行对象,然后以两种不同的方式初始化它们。那么,这是否意味着您可以在运行时将这些可运行对象传递给其他事物?
我想将代码传递给预先存在的线程,以便在该线程的循环中执行。我环顾四周,据我所知,您可能想要创建一个专用的可运行类,如下所示:
public class codetobesent implements Runnable
{
public void run()
{
..morecodehere.
}
...insertcodestuffhere
}
但是我如何将其传递给已经运行的线程?假设我正在尝试制作一个游戏,并且我有一些特别的事情希望渲染器在其线程中执行。我如何将此可运行对象传递给该线程并让它正确运行此数据?
我当前的渲染线程实现如下,我将其从教程网站上拉下来,到目前为止它运行得很好。但我想知道如何将东西传递给它,这样我就可以运行比预设循环中更多的东西。
class RenderThread extends Thread
{
private SurfaceHolder _curholder;
private UserView curview;
private boolean runrender = false;
public RenderThread (SurfaceHolder holder, UserView thisview)
{ //Constructor function - This gets called when you create a new instance of this object.
curview = thisview;
_curholder = holder;
}
public SurfaceHolder getThreadHolder()
{
return _curholder;
}
public void setRunning(boolean onoff)
{
runrender = onoff;
}
@Override
public void run()
{
Canvas c;
while (runrender)
{
c = null; //first clear the object buffer.
try
{
c = _curholder.lockCanvas(null); //lock the canvas so we can write to it
synchronized (_curholder)
{//we sync the thread with the specified surfaceview via its surfaceholder.
curview.onDraw(c);
}
}
finally
{
// do this in a finally so that if an exception is thrown
// during the above, we don't leave the Surface in an
// inconsistent state
if (c != null)
{
_curholder.unlockCanvasAndPost(c);
}
}
}
}
}
最佳答案
处理程序线程实现。
private void testWorker(){
WorkerThread worker = new WorkerThread();
worker.start();
for (int i = 0; i < 10; i++) {
worker.doRunnable(new Runnable() {
public void run() {
Log.d("demo", "just demo");
try {
Thread.sleep(1000);//simulate long-duration operation.
} catch (InterruptedException e) {
e.printStackTrace();
}
};
});
}
}
private class WorkerThread extends HandlerThread implements Callback {
private Handler mHandler;
public WorkerThread() {
super("Worker");
}
public void doRunnable(Runnable runnable) {
if (mHandler == null) {
mHandler = new Handler(getLooper(), this);
}
Message msg = mHandler.obtainMessage(0, runnable);
mHandler.sendMessage(msg);
}
@Override
public boolean handleMessage(Message msg) {
Runnable runnable = (Runnable) msg.obj;
runnable.run();
return true;
}
}
关于android - 将可运行对象传递给预先存在的线程以在 Android/Java 中运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10560166/