[英]Thread not running, and why is jframe setresizeable not working
为什么这个程序不起作用? (它不会打印“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();
}
}
我正在努力学习线程,这是我所学过的一个,如果不是最难的话。 OOP与此xD无关
当你调用client.start();
时,你会以错误的方式执行此操作client.start();
它将调用Client
类中的start函数,并在该函数中创建一个新的线程类实例,其默认run
方法为空
你可能是指这段代码:
public synchronized void start() {
running = true;
thread = new Thread(this);
thread.start(); // start the thread
}
我希望这对你有帮助
因为这
new Thread("display");
将其更改为
new Thread(this)
我只是希望你知道你在做什么。
您已经创建了一个通用(读取BLANK)线程对象。 您需要将您的类作为参数传入。
thread = new Thread(this);
这会将run方法绑定到Thread对象。 线程的名称通常不那么重要。 请参阅此示例
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.