目前我正在嘗試構建一個蛇遊戲作爲我在java中的第一個項目,並且正在使用線程。我希望有一個對象在到達屏幕邊界時等待,然後在鍵輸入進入時繼續通知另一個方向。 在底部我調用notify()函數,但沒有任何反應,並且線程繼續處於wait()狀態。任何幫助將非常感激。java無法通知()線程?
package com.foreverblu.snake;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class snakeobject extends JPanel{
int x = 0;
int y = 0;
int z = 0;
int a = 0;
Thread animationThread;
Thread notifyThread;
public void paintComponent(Graphics g) {
super.paintComponents(g);
this.setBackground(Color.black);
g.setColor(Color.GREEN);
g.fill3DRect(x, y, 30, 30, true);
}
public void keepGoing() {
animationThread = new Thread(create);
notifyThread = new Thread(create2);
}
Runnable create = new Runnable() {
public void run() {
synchronized(this) {
while(z>=0 || z<=3) {
if(z==2 && y>0) {
y-=30;
repaint();
try{Thread.sleep(500);} catch (Exception ex) {}
}else if(z==1 && y<=450) {
y+=30;
repaint();
try {Thread.sleep(500);} catch (Exception ex) {}
}else if(z==0 && x<=450) {
x+=30;
repaint();
try{Thread.sleep(500);} catch (Exception ex) {}
}else if(z==3 && x>0) {
x-=30;
repaint();
try{Thread.sleep(500);} catch (Exception ex) {}
}else{
notifyThread.notify();
}
}
}
}
};
Runnable create2 = new Runnable() {
public void run() {
synchronized(this) {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
animationThread.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
do{try{Thread.sleep(500);} catch (Exception ex) {}
continue;
}while(a==0);
if(a==1) {
System.out.println("Notified");
a=0;
animationThread.notifyAll();
}
}
}
};
}
其他職業: package com.foreverblu.snake;
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
public class snakeframe extends JFrame{
int z = 0;
snakeobject swag = new snakeobject();
public snakeframe() {
super("The Great Title");
swag.keepGoing();
swag.notifyThread.start();
swag.animationThread.start();
addKeyListener(new KeyAdapter() {
public void keyPressed(KeyEvent e) {
if(swag.animationThread.getState()==Thread.State.WAITING) {
swag.a=1;
System.out.println("Swag");
}
if(swag.animationThread.getState()==Thread.State.RUNNABLE) {
System.out.println("RUNNABLE");
}
if(e.getExtendedKeyCode()==e.VK_DOWN) {
swag.z=1;
}else if(e.getExtendedKeyCode()==e.VK_UP) {
swag.z=2;
}else if(e.getExtendedKeyCode()==e.VK_LEFT) {
swag.z=3;
}else if(e.getExtendedKeyCode()==e.VK_RIGHT) {
swag.z=0;
}
}
});
add(swag);
}
}
嗯,你使用的等待一個/通知不正確。在一臺監視器上同步,但通知另一臺監視器。如果執行任何相關代碼,您應該會收到異常。你不需要使用額外的線程,因爲EDT和主線程就足夠了。 – Kayaman
你提到這是你的第一個Java項目。我建議你先去掉線程,然後再去尋求更多的基本設計。多線程不是你應該開始的事情。 – Gima