class A
implements Runnable
{
int time;
A( int time )
{
this.time = time;
}
public void run()
{
for ( int i = 0; i < 3; i++ )
{
System.out.println( Thread.currentThread().getName() );
try
{
Thread.sleep( time );
}
catch ( Exception e )
{
System.out.println( e );
}
;
}
}
}
class Check
{
public static void main( String args[] )
throws Exception, Throwable
{
Thread t = Thread.currentThread();
A a1 = new A( 200, t );
A a2 = new A( 100, t );
A a3 = new A( 500, t );
Thread t1 = new Thread( a1 );
Thread t2 = new Thread( a2 );
Thread t3 = new Thread( a3 );
t1.start();
t2.start();
t3.start();
try
{
Thread.sleep( 5000 );
}
catch ( Exception e )
{
}
;// => i have to interrupt this sleep.
System.out.println( "Main Thread's rest of the code" );
}
}
我希望在所有用户线程都被竞争时中断主线程的休眠。如果主线程在用户线程完成之前唤醒,那么它必须与其他用户线程同时执行。 p.s:这可以使用java中的Object类来完成。所以请用这个给我一些建议。
答案 0 :(得分:2)
使用ExecutorService会简单得多,但假设您需要直接使用Threads ....
您需要做的只是
t1.join();
t2.join();
t3.join();
等待所有线程完成。
您可以使用run()
稍微优化一下t1.start();
t2.start();
t3.run(); // use the current thread
t1.join();
t2.join();
// only need to join two threads.
如果主线程提前醒来,那么我必须同时执行主线程的其余代码以及用户线程..
假设您要等待后台线程但不超过5秒(我无法想象您为什么会这样做但是......)
long end = System.currentTimeMillis() + 5000;
t1.join(Math.max(1, end - System.currentTimeMillis()));
t2.join(Math.max(1, end - System.currentTimeMillis()));
t3.join(Math.max(1, end - System.currentTimeMillis()));
主线程将等待最多5秒,如果线程完成则提前完成,但如果没有则会放弃等待。
使用ExecutorService执行类似操作
ExecutorService es = Executors.newCachedThreadPool();
es.submit(new A(200));
es.submit(new A(100));
es.submit(new A(500));
es.shutdown();
es.awaitTermination(5, TimeUnit.SECONDS);
答案 1 :(得分:0)
我建议使用类似ExecutorService
的内容。你可以这样做:
ExecutorService executorService = new ThreadPoolExecutorService(...);
executorService.submit(new A(200));
executorService.submit(new A(100));
executorService.submit(new A(500));
executorService.shutdown();
executorService.awaitTermination(/* some timeout */);
System.out.println("Main Thread's rest of the code");
这避免了你实际上不得不考虑协调各个线程的执行,并且更容易处理grotty边缘情况(例如,如果一个线程永远不会终止)。