JAVAスレッドjoinの使い方
2913 ワード
package self;
/*
* , , ,
*
*/
public class TestThread {
public static void main(String[] args){
//
Thread minorThread = new Thread(new MinorThread());
// ,
Thread majorThread = new Thread(new MajorThread(minorThread));
majorThread.start();
}
}
class MajorThread implements Runnable {
Thread thread = null;
public MajorThread(Thread thread){
this.thread = thread;
}
@Override
public void run(){
long startTime = System.currentTimeMillis();
//
thread.start();
while(thread.isAlive()){
try {
System.out.println("thread is Alive ");
/*
* join(1000) 1s, thread
* join() , thread ,
*/
thread.join(1000);
long runningTime = System.currentTimeMillis();
long endTime = (runningTime-startTime)/1000;
/*
* 3s thread , kill thread
*/
if(endTime>3){
//
thread.interrupt();
System.out.println(" 3s thread , kill thread ");
// thread
thread.join();
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
System.out.println("thread is not Alive ... finish!");
}
}
class MinorThread implements Runnable {
String[] massages = { "ji hai bo...",
"zhang xiao yan...",
"hello world...",
"OK OK!",
"too too" };
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + " is start");
try{
for (String massage : massages) {
System.out.println(massage);
Thread.sleep(1000);
}
} catch (InterruptedException e) {
System.out.println("Thread interrupted...................");
e.printStackTrace();
}
/*while (true) {
//
for (String massage : massages) {
System.out.println(massage);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
return;
}
}
if (Thread.interrupted()){
System.out.println("Thread interrupted");
try {
throw new InterruptedException();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}*/
}
}