java 一个线程等待另一个线程_java – 执行两个线程,在主线程继续时等待另一个线程...

博客围绕Java中如何实现两个线程先后执行展开,即thread1先执行,thread2在thread1结束时启动,且main方法线程可继续工作。博主尝试了join()和ExecutorService,但都存在问题,还说明了此需求源于数据库表复制,避免完整性错误。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如何启动thread1首先执行的两个线程,thread2在thread1结束时启动,而main方法线程可以继续工作而不锁定另外两个?

我已经尝试了join()但是它需要从线程调用,它必须等待另一个,没有办法像thread2.join(thread1)那样做;

如果我在main()中调用连接,那么我有效​​地停止执行主线程,而不仅仅是thread2.

因此,我尝试使用ExecutorService,但同样的问题.

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.TimeUnit;

public class Test

{

public static void main(String args[]) throws InterruptedException

{

System.out.println(Thread.currentThread().getName() + " is Started");

class TestThread extends Thread

{

String name;

public TestThread(String name)

{

this.name = name;

}

@Override

public void run()

{

try

{

System.out.println(this + " is Started");

Thread.sleep(2000);

System.out.println(this + " is Completed");

}

catch (InterruptedException ex) { ex.printStackTrace(); }

}

@Override

public String toString() { return "Thread " + name; }

}

ExecutorService executor = Executors.newCachedThreadPool();

executor.execute(new TestThread("1"));

boolean finished = executor.awaitTermination(1, TimeUnit.HOURS);

if(finished)

{

//I should execute thread 2 only after thread 1 has finished

executor.execute(new TestThread("2"));

}

//I should arrive here while process 1 and 2 go on with their execution

System.out.println("Hello");

}

}

#EDIT:为什么我需要这个:

我需要这个,因为Thread1将数据库表中的元素复制到另一个数据库中,thread2必须复制一个引用从thread1复制的表的链接表.

因此,thread2只有在thread1完成时才开始填充其链接表,否则数据库会给出完整性错误.

现在想象一下,由于复杂的链接表,我有几个不同优先级的线程,你有一个想法.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值