简体   繁体   中英

How to create an object every 3 seconds using a thread in Java?

I am trying to make a game where an enemy object spawns every 3 seconds and tries to chase your player, but I don't know how I will make a generator that creates an enemy object every 3 seconds.

I already tried this by creating a thread that runs every 3 seconds, but it gives me an error that says

No OpenGL context found in the current thread.

I'm using OpenGL to program displays and textures.

You can use a ScheduletExecutorService and schedule at fixed rate every 3 seconds. It will not create a new thread every 3 seconds, instead it uses only one additional thread to create all the objects you need.

ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(new Runnable() {
    public void run() {
       // Create your object;
    }
}, 0, 3, TimeUnit.SECONDS);

To see more:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM