[英]Executing main class while thread sleeps - java
Can someone help me understand how threads function in java. 有人可以帮助我了解线程如何在Java中起作用。
I have a main class: 我有一个主要的班级:
public static void main(String[] args) {
Runnable r = new TestThread();
new Thread(r).start();
executor.execute(r);
System.out.println("Hey the thread has ended")
}
and a thread class: 和一个线程类:
public class TestThread implements Runnable {
public class TestThread() {
sleep(20000);
}
@Override
public void run() {
// TODO Auto-generated method stub
}
}
How can I get the phrase:"Hey the thread has ended" without having to wait while the thread sleeps? 我如何获得这样的短语:“嘿,线程已结束”而不必等待线程休眠?
You can do: call the start method of the thread class, and in the Run implementation make the thread sleep... 您可以执行以下操作:调用线程类的start方法,然后在Run实现中使线程处于睡眠状态...
notice that your app is going to terminate before the Thread returns from the sleep and continues 请注意,在线程从睡眠状态返回并继续之前,您的应用程序将终止
public class TestThread implements Runnable {
@Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(20000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void setParameter(String string) {
// TODO Auto-generated method stub
}
}
public static void main(String[] args) {
TestThread r = new TestThread();
r.setParameter("myParameterHere");
Thread t = new Thread(r);
t.setName("asdas");
t.start();
System.out.println("Hey the thread has ended");
}
Here it is in what is arguably it's most simple form. 可以说这是最简单的形式。
public class TestThread implements Runnable {
@Override
public void run() {
try {
Thread.sleep(20000);
} catch (InterruptedException ex) {
}
}
}
public void test() throws InterruptedException {
Runnable r = new TestThread();
Thread t = new Thread(r);
t.start();
// No it hasn't!
//System.out.println("Hey the thread has ended");
t.join();
// It has now!
System.out.println("Hey the thread has ended");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.