/ / Thread ne fonctionne pas, et pourquoi jframe setresizeable ne fonctionne pas - java, multithreading, swing, jframe

Thread not running, and why is jframe setresizeable not working - java, multithreading, swing, jframe

Pourquoi ce programme ne fonctionne-t-il pas? (Il n'imprime pas "Running ...")

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();
}
}

J'essaye d'apprendre des fils, et c'est une des choses, sinon la plus difficile, que j'aie jamais apprise. La POO n'est rien pour ce xD

Réponses:

1 pour la réponse № 1

À cause de ce

new Thread("display");

Le changer en

new Thread(this)

J'espère juste que vous savez ce que vous faites.


2 pour la réponse № 2

tu fais ça de la mauvaise manière, quand vous appelez client.start(); il appellera la fonction de démarrage dans le Client class et dans cette fonction, vous créez une nouvelle instance de classe de thread qui a la valeur par défaut run méthode qui est vide

vous pouvez dire ce code:

public synchronized void start() {
running = true;
thread = new Thread(this);
thread.start(); // start the thread
}

J'espère que cela vous aidera


0 pour la réponse № 3

Vous avez créé un objet thread générique (lecture BLANK). Vous devez passer votre classe en paramètre.

thread = new Thread(this);

Cela liera votre méthode d'exécution à l'objet Thread. Le nom du fil n'est généralement pas si important. Faire référence à cet exemple