简体   繁体   中英

Thread not running, and why is jframe setresizeable not working

Why is this program not working? (It doesn't print "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();
    }
}

I'm trying to learn threads, and it's one, if not the most hard, thing I ever have learned. OOP is nothing to this xD

you do this in wrong way, when you call client.start(); it will call start function in the Client class and in that function you make a new instance of thread class that has the default run method that is empty

you may mean this code:

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

I hope this help you

Because of this

new Thread("display");

Change it to

new Thread(this)

I just hope you know what you're doing.

You have created a generic (read BLANK) thread object. You need to pass in your class as a parameter.

thread = new Thread(this);

This will bind your run method to the Thread object. The name of the thread is usually not so important. Refer to this example

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM