このプログラムが機能しないのはなぜですか? (「実行中...」は出力されません)
package eu.inmensia.learn;
import java.awt.Canvas;
import java.awt.Dimension;
import javax.swing.JFrame;
public class Client extends Canvas implements Runnable {
private static final long serialVersionUID = 1L;
public static final int WIDTH = 300;
public static final int HEIGHT = WIDTH / 16 * 9;
public static final short SCALE = 3;
private Thread thread;
private JFrame frame = new JFrame();
private boolean running = false;
public Client() {
Dimension size = new Dimension(WIDTH * SCALE, HEIGHT * SCALE);
setPreferredSize(size);
}
public synchronized void start() {
running = true;
thread = new Thread("display");
thread.start(); // start the thread
}
public synchronized void stop() {
running = false;
try{
thread.join(); // end the thread
}catch(InterruptedException e){ e.printStackTrace(); }
}
public void run() {
while(running){
System.out.println("Running...");
}
}
public static void main(String[] args) {
Client client = new Client();
client.frame.setResizeable(false);
client.frame.setTitle("Program test");
client.frame.add(client);
client.frame.pack();
client.frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
client.frame.setLocationRelativeTo(null);
client.frame.setVisible(true);
client.start();
}
}
私はスレッドを学ぼうとしていますが、これは私が今までに学んだ中で最も難しいことではないにしても、その1つです。 OOPはこのxDには何もありません
回答:
回答№1は1このため
new Thread("display");
それに変更する
new Thread(this)
私はあなたがあなたが何をしているのかを知っていることを願っています。
回答№2については2
あなたはこれを間違った方法で行います、 あなたが電話するとき client.start();
でstart関数を呼び出します Client
クラスとその関数で、デフォルトのスレッドクラスの新しいインスタンスを作成します run
空のメソッド
あなたはこのコードを意味するかもしれません:
public synchronized void start() {
running = true;
thread = new Thread(this);
thread.start(); // start the thread
}
これがあなたに役立つことを願って
回答№3の場合は0
汎用(空白を読み取る)スレッドオブジェクトを作成しました。クラスをパラメータとして渡す必要があります。
thread = new Thread(this);
これにより、runメソッドがThreadオブジェクトにバインドされます。通常、スレッドの名前はそれほど重要ではありません。参照する この例