简体   繁体   中英

Thread.start() doesn't initialize run()

I have some problems with my code. For some reason my thread.start() doesn't activate my run() method. In pure desperation I have simply replaced my code in run() with a printing function, but nothing is being printed. Can someone help me by explaining what is wrong in my code?

public class Screen extends JPanel implements Runnable{
    Thread thread = new Thread();

    Frame frame;

    public Screen(Frame frame){
        this.frame = frame;
        frame.setSize(horizontal * 25 + 24 , (vertical) * 25 + 48);
        this.frame.addKeyListener(new KeyHandler(this));
        thread.start();
    }
    public void run(){
        System.out.println("Boom");
    }
}

I got a lot of stuff in between and under this code, but this is the only part essential to the thread and frame.

You must pass the Thread a Runnable . Since thread is an instance variable and the class implements Runnable I guess you want to do this:

Thread thread = new Thread(this);

But be careful when calling overridable methods from a constructor and be more careful if these methods are called by a separate thread that runs the code in parralel to the constructor initialization. It might run while the constructor still initializes the object. Think about what will happen if you subclass Screen , override the run method and the run method accesses properties of the superclass Screen while it is initializing.

Also see What's wrong with overridable method calls in constructors?

This is because your thread doesn't know about the run method. You can do it by changing

Thread thread = new Thread();

to

Thread thread = new Thread(this);

because your class is an instance of Runnable.

ps try to avoid messing with threads and Swing. Use SwingWorkers if you really have to.

Thread needs a Runnable instance, which has run() method to call. But you are not providing Runnable instance to Thread .

Do Thread t = new Thread(this);

You are creating a simple thread.

Thread thread = new Thread();

It does call run() method but of class Thread and not your Screen class runnable implementation.

You can do

Thread thread = new Thread(new Screen());

You have two solutions:
1) Using the override run method in your class

Thread thread = new Thread(this);

2) Using new Runnable

Thread th = new Thread(new Runnable() {

        @Override
        public void run() {
            // your code

        }
    });

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