为什么这个程序不起作用? (它不会打印“正在运行......”)
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无关。
答案 0 :(得分:2)
client.start();
时,它将在Client
类中调用start函数,并在该函数中创建一个新的线程类实例,其默认的run
方法是空的
你可能是指这段代码:
public synchronized void start() {
running = true;
thread = new Thread(this);
thread.start(); // start the thread
}
我希望这可以帮到你
答案 1 :(得分:1)
因为这个
new Thread("display");
将其更改为
new Thread(this)
我希望你知道你在做什么。
答案 2 :(得分:0)
您已创建了一个通用(读取BLANK)线程对象。您需要将您的课作为参数传递。
thread = new Thread(this);
这会将您的run方法绑定到Thread对象。线程的名称通常不那么重要。请参阅this example