(可能)相当简单的Java多线程问题

(可能)相当简单的Java多线程问题,java,multithreading,runtime-error,Java,Multithreading,Runtime Error,我正在制作一个平台,我让玩家每30毫秒跳过去一次,向上增加一点力。我想我应该使用多线程,因为我以前做过一点,而且看起来很简单。无论如何,我试过这个: public void jump() { new Runnable() { public void run() { for (int i = 0; i <= jumpForce; i++) { velocity.y++; Syste

我正在制作一个平台,我让玩家每30毫秒跳过去一次,向上增加一点力。我想我应该使用多线程,因为我以前做过一点,而且看起来很简单。无论如何,我试过这个:

public void jump() {
    new Runnable() {
        public void run() {
            for (int i = 0; i <= jumpForce; i++) {
                velocity.y++;
                System.out.println("Adding force");
                try {
                    wait(30);
                } catch (InterruptedException e) {}
            }
        }
    }.run();
}

我不知道这意味着什么,有人能告诉我我做错了什么吗

此方法只能由作为的所有者的线程调用 此对象的监视器。请参阅notify方法以获取对 线程成为监视器所有者的方式

如果您拥有具有同步块的监视器,请将代码更改为:

synchronized (this) {
  wait(30);
}

javadoc表示等待:

此方法只能由作为的所有者的线程调用 此对象的监视器。请参阅notify方法以获取对 线程成为监视器所有者的方式

如果您拥有具有同步块的监视器,请将代码更改为:

synchronized (this) {
  wait(30);
}

您不是多线程,因为您没有创建任何线程。
Runnable正在运行它的同一线程中运行。如果要创建新线程,必须使用
new Thread(new Runnable())
显式创建,并使用
Thread\start()

无论如何,您可能只是想安排一个任务,以便更好地使用ScheduledExecutorService:

ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor();
ex.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
        // do something
    }
}, 0, 30, TimeUnit.SECONDS);

您不是多线程,因为您没有创建任何线程。
Runnable正在运行它的同一线程中运行。如果要创建新线程,必须使用
new Thread(new Runnable())
显式创建,并使用
Thread\start()

无论如何,您可能只是想安排一个任务,以便更好地使用ScheduledExecutorService:

ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor();
ex.scheduleAtFixedRate(new Runnable() {
    @Override
    public void run() {
        // do something
    }
}, 0, 30, TimeUnit.SECONDS);

如果希望在不同的线程中执行此代码,则应调用Runnable的
run()
方法。您应该做的是创建一个线程实例,并将可运行实现放入其构造函数中。 然后调用
.start()

public void jump(){
新线程(newrunnable()){
公开募捐{

对于(int i=0;i如果希望在不同的线程中执行此代码,则不应调用Runnable的
run()
方法。您应该创建线程的实例,并将Runnable实现放入其构造函数中。 然后调用
.start()

public void jump(){
新线程(newrunnable()){
公开募捐{

对于(int i=0;i)您需要在类减速中
实现Runnable
。您这样做了吗?在哪个类上?Runnable或包含
jump()
的类?仅调用
Runnable#run()
不足以创建新线程。您需要从Runnable创建
thread
,然后
start()
it。为什么不使用
ScheduledExecutorService
?而且您实际上不是“多线程”,因为线程与启动runnable的线程相同。您可能需要在类减速中实现runnable
。您这样做了吗?在哪个类上?runnable或包含
jump()的类
?单独调用
Runnable#run()
不足以创建一个新线程。您需要从Runnable创建一个
线程,然后
start()
它。为什么不使用
ScheduledExecutorService
?而实际上您不是“多线程”,因为线程与启动runnable的线程相同。可能的重复我已经回答了IllegalMonitorStateException-您的问题。但是看到另一个答案:您的代码不是多线程的,创建runnable还不够我已经回答了IllegalMonitorStateException-您的问题。但是看到另一个答案:您的代码是不是多线程的,创建一个Runnable是不够的,它用于每30秒运行一次Runnable。因此,您不必等待并循环。它只需再次运行Runnable。它用于每30秒运行一次Runnable。因此,您不必等待并循环。它只需再次运行Runnable。