Here's my code:
public class DJ {
static Thread djThread = new DJPlayThread();
public static void play(){
djThread.start();
}
}
But once that thread is started, how can I run a method that is inside of the DJPlayThread
class?
Thanks.
Here is a simple example of how to do what you ask:
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);
}
}
Should print out:
Playing Music
Playing Music
Playing Music
Playing Music
Playing Music
Playing Music
Playing Music
Playing Music
Playing Music
Playing Music
Be very careful about the thread safety when exchanging information between threads. There are some weird things that happen when accessing and modifying variables across thread contexts.
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.