[英]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.