访问线程并在Thread类中运行一个方法

Dan*_*247 0 java multithreading class

这是我的代码:

public class DJ {
    static Thread djThread = new DJPlayThread();

    public static void play(){
        djThread.start();
    }
}
Run Code Online (Sandbox Code Playgroud)

但是一旦该线程启动,我该如何运行DJPlayThread类内部的方法?

谢谢.

Dav*_*amp 5

这是一个如何做你问的简单例子:

public class ThreadControl {

    public static void main(String[] args) {
        MyRunnable myRunnable = new MyRunnable("MyRunnable");
        Thread thread = new Thread(myRunnable);
        thread.setDaemon(true);
        thread.start();

        myRunnable.whoAmI();//call method from within thread

        try {
            Thread.sleep(6000);
        } catch (InterruptedException e) {
        }
        myRunnable.isStopped.set(true);//stop thread
    }

 static class MyRunnable implements Runnable {
        public String threadName;
        public AtomicBoolean isStopped=new AtomicBoolean(false);

        public MyRunnable() {
        }

        public MyRunnable(String threadName) {
            this.threadName = threadName;
        }

        public void run() {
            System.out.println("Thread started, threadName=" + this.threadName + ", hashCode="
                    + this.hashCode());

            while (!this.isStopped.get()) {
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                }
                System.out.println("Thread looping, threadName=" + this.threadName + ", hashCode="
                        + this.hashCode());
            }
        }

        public void whoAmI() {
            System.out.println("whoAmI, threadName=" + this.threadName + ", hashCode="
                    + this.hashCode());
        }

    }

}
Run Code Online (Sandbox Code Playgroud)

  • @DavidKroukamp我认为这与问题有关.我们应该提供完整的例子.在这种情况下,您只需要使用AtomicBoolean,make isStopped volitile或提供一个同步的getter/setter对来保证线程安全. (2认同)