传参
class MyThread1 extends Thread {
@Setter
private String name;
public MyThread1 ( String name) {
this . name = name;
}
public void process ( String name) {
this . name = name;
}
@Override
public void run ( ) {
System. out. println ( name) ;
}
}
处理返回值
class CycleWait implements Runnable {
public String value;
@Override
public void run ( ) {
try {
Thread. sleep ( 5000 ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
}
value = "we have date now" ;
}
}
主线程等待法
CycleWait cw = new CycleWait ( ) ;
Thread t = new Thread ( cw) ;
t. start ( ) ;
while ( cw. value == null) {
Thread. sleep ( 100 ) ;
}
System. out. println ( "value :" + cw. value) ;
使用Thread类的join()阻塞当前线程以等待子线程处理完毕
CycleWait cw = new CycleWait ( ) ;
Thread t = new Thread ( cw) ;
t. start ( ) ;
t. join ( ) ;
System. out. println ( "value :" + cw. value) ;
通过Callable接口实现:通过FutureTask Or 线程池获取
class MyCallable implements Callable < String> {
@Override
public String call ( ) throws Exception {
String value = "test" ;
System. out. println ( "Ready to word" ) ;
Thread. sleep ( 5000 ) ;
System. out. println ( "task dene" ) ;
return value;
}
}
Future方式
FutureTask< String> task = new FutureTask < > ( new MyCallable ( ) ) ;
new Thread ( task) . start ( ) ;
if ( ! task. isDone ( ) ) {
System. out. println ( "正在等待。。。" ) ;
}
System. out. println ( task. get ( ) ) ;
线程池
ExecutorService newCachedThreadPoll = Executors. newCachedThreadPool ( ) ;
Future< String> future = newCachedThreadPoll. submit ( new MyCallable ( ) ) ;
if ( ! future. isDone ( ) ) {
System. out. println ( "正在等待。。。" ) ;
}
try {
System. out. println ( future. get ( ) ) ;
} catch ( InterruptedException e) {
e. printStackTrace ( ) ;
} catch ( ExecutionException e) {
e. printStackTrace ( ) ;
} finally {
newCachedThreadPoll. shutdown ( ) ;
}