Multithreading – JPA and threads in the playback frame
•
Java
I'm trying to create a multithreaded server The problem is that I received the following error:
What I want to do is access dB from the new thread. Here is the code
package controllers; import java.util.Iterator; import java.util.List; import models.Ball; public class MainLoop extends Thread { @Override public void run() { List<Ball> balls; new Ball(5,5,2,10,15); while (true){ balls = Ball.all().fetch(); //Here throws an exception for (Iterator iterator = balls.iterator(); iterator.hasNext();) { Ball ball = (Ball) iterator.next(); ball.applyForces(); } } } }
Any ideas?
Solution
Instead of using normal threads, use jobs:
@OnApplicationStart public class MainLoop extends Job { public void doJob() { new BallJob().Now(); } }
And players:
public class BallJob extends Job { public void doJob() { List<Ball> balls; new Ball(5,15); while (true){ balls = Ball.all().fetch(); for (Iterator iterator = balls.iterator(); iterator.hasNext();) { Ball ball = (Ball) iterator.next(); ball.applyForces(); } } }
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码