[code=java]
public class MyJoin {
public static void main(String[] args) throws InterruptedException {
Th2 th2=new Th2();
th2.setName("B");
th2.start();
th2.join();
//th2对象先获得锁对象,
//th2中的th1获取CPU资源,锁对象
System.out.println("Main");
}
}
class Th1 extends Thread{
@Override
public void run() {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(this.getName());
super.run();
}
}
class Th2 extends Thread{
@Override
public void run() {
Th1 th1=new Th1();
th1.setName("A");
th1.start();
System.out.println(this.getName());
try {
th1.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(this.getName());
super.run();
}
}
B
A
B
Main
[/code]
三种方式是
extend Thread;
implement Runable接口
implement Callable接口
使用Future.run执行,或者线程池去执行
public static void main(String [] arg) throws InterruptedException, ExecutionException{
// 这种方式 穿件的线程需要使用 FutureTask 类进行包装,才能使用 Thread.start() 启动
// 例如
Callable<String> t3 = new MyCall();
// t3.wait();
FutureTask<String> task = new FutureTask<String>(t3);
new Thread(task).start();
// 然后通过 task.get() 函数能够获取线程执行的结果(返回值)
// 如果线程没有执行完,get() 函数会一直阻塞等到线程执行结束
String val = task.get();
// 另外可以通过 task.isDone() 函数校验是否执行完 - 该函数不阻塞
if(task.isDone()){
String val1 = task.get();
System.out.println(val1);
}else{
System.out.println("未执行完");
}
// 配合线程池使用 返回 Future 可以通过 Future 获取执行结果
ExecutorService executor = Executors.newFixedThreadPool(2);//任务较重的服务器,
Future<String> val2 = executor.submit(t3);
System.out.println(val2.get());
}