Reputation: 61
Can someone help me understand how threads function in 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?
Upvotes: 0
Views: 70
Reputation: 65821
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");
}
Upvotes: 0
Reputation: 48278
You can do: call the start method of the thread class, and in the Run implementation make the thread sleep...
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");
}
Upvotes: 1