java线程内使用while,Java:卡在后台线程的while循环中

I'm using LibGDX AsyncExecutor and the following function is called in a background thread. 'tasksForTheMainThread' is the static array of Runnable, which executes its not yet executed elements during each call of the update function in the main thread. The function 'createBox' of 'modelBuilder' creates and returns an object of the class 'Model'.

Briefly explaining, this code executes in the second thread and sends a piece of code (function 'run()') to be used in the first thread. After it's sent, the second thread is frozen until the moment the code in "run()" is completed and the Model object is created (or at least it's supposed to be like that).

However, it works as expected only when the while loop (which just waits until the object is created in the main thread) contains the logging bit (Gdx.app.log("TAG","2");). When it's empty, the second thread freezes forever and never reaches 'point A' even after the creation of the Model object.

Why and how logging can influence that? And why isn't the programme working without it?

void secondThreadFunction()

{

Model model = null;

ChunkManager.tasksForTheMainThread.add(new Runnable()

{

@Override

public void run()

{

model = modelBuilder.createBox(size.x, size.y, size.z, GL20.GL_LINES,

new Material(ColorAttribute.createDiffuse(Color.YELLOW)),

VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal);

}

});

while (model == null)

{

//Gdx.app.log("TAG","2");

}

//point A

}

解决方案

You cannot modify a local variable that has been captured to an inner class. Since it has been "captured", you will operate on a copy of the value and it will never be non-null, causing the endless loop. Also note that you are busy-waiting in a tight loop. It might be better to use a Future of some kind.

void secondThreadFunction()

{

AtomicReference model = new AtomicReference();

ChunkManager.tasksForTheMainThread.add(new Runnable()

{

@Override

public void run()

{

model.set(modelBuilder.createBox(size.x, size.y, size.z, GL20.GL_LINES,

new Material(ColorAttribute.createDiffuse(Color.YELLOW)),

VertexAttributes.Usage.Position | VertexAttributes.Usage.Normal));

}

});

while (model == null)

{

//Gdx.app.log("TAG","2");

}

//point A

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值