在线程休眠时执行 main class - java
Executing main class while thread sleeps - java
谁能帮我理解线程在 java 中的工作原理。
我有一个主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")
}
和一个线程class:
public class TestThread implements Runnable {
public class TestThread() {
sleep(20000);
}
@Override
public void run() {
// TODO Auto-generated method stub
}
}
我怎样才能得到短语:"Hey the thread has ended"而不必在线程休眠时等待?
你可以这样做:
调用线程class的start方法,在运行实现中让线程休眠...
请注意,您的应用程序将在线程 returns 进入睡眠状态之前终止并继续
运行启用class
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");
}
这是可以说是最简单的形式。
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");
}
谁能帮我理解线程在 java 中的工作原理。
我有一个主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")
}
和一个线程class:
public class TestThread implements Runnable {
public class TestThread() {
sleep(20000);
}
@Override
public void run() {
// TODO Auto-generated method stub
}
}
我怎样才能得到短语:"Hey the thread has ended"而不必在线程休眠时等待?
你可以这样做: 调用线程class的start方法,在运行实现中让线程休眠...
请注意,您的应用程序将在线程 returns 进入睡眠状态之前终止并继续
运行启用class
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");
}
这是可以说是最简单的形式。
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");
}