簡體   English   中英

訪問線程並在Thread類中運行方法

[英]Access thread and run a method inside Thread class

這是我的代碼:

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

    public static void play(){
        djThread.start();
    }
}

但是,一旦啟動該線程,如何運行DJPlayThread類內部的方法?

謝謝。

這是一個簡單的示例,說明您如何做:

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());
        }

    }

}
public class DJ {
    private DJPlayThread djThread = new DJPlayThread();

    public void play() throws InterruptedException {
        djThread.start();

        Thread.sleep(10000);

        djThread.stopMusic();
    }

    public static void main(String[] args){
        try{
            new DJ().play();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public class DJPlayThread extends Thread{

    private AtomicBoolean running = new AtomicBoolean(true);

    @Override
    public void run() {
        while(running.get()){
            System.out.println("Playing Music");
            try {
                sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    public void stopMusic(){
        //be careful about thread safety here
        running.set(false);
    }
}

應該打印出來:

Playing Music 
Playing Music 
Playing Music 
Playing Music 
Playing Music
Playing Music 
Playing Music 
Playing Music 
Playing Music 
Playing Music

在線程之間交換信息時,請特別注意線程安全性。 在線程上下文之間訪問和修改變量時,會發生一些奇怪的事情。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM