创建三个线程并依次执行

昨天做笔试题的时候遇到一个多线程的问题,需要我们创建三个线程,操作同一个String,并且依次赋值,最后打印。

操作同一个String只需要我们同步或者加锁就可以保证其原子性了,可是如何保证顺序执行呢?

一、join方法

我们来看api文档中的说明,等待本线程死亡。
也就是说,我们在其他线程run方法内部调用本线程的join方法,其他线程必须等待本线程死亡后才能继续执行后续的逻辑代码块。

public final void join()
                throws InterruptedException
Waits for this thread to die.
An invocation of this method behaves in exactly the same way as the invocation

join(0)
Throws:
InterruptedException - if any thread has interrupted the current thread. The interrupted status of the current thread is cleared when this exception is thrown.

所以我们可以这么写:

        final Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    System.out.print(Thread.currentThread().getName() + " 1 ");
                }catc
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
可以使用多线程执行3个函数,这样可以提高程序的效率和响应速度。以下是一个简单的示例代码,使用C#的Thread类来创建一个新线程,并在该线程执行3个函数: ``` csharp using System; using System.Threading; class Program { static void Main(string[] args) { // 创建一个新线程 Thread t = new Thread(new ThreadStart(ExecuteFunctions)); // 启动线程 t.Start(); // 主线程继续执行其他操作 Console.WriteLine("Main thread is doing something else..."); // 等待新线程执行完毕 t.Join(); // 程序结束 Console.WriteLine("All functions have been executed."); Console.ReadLine(); } static void ExecuteFunctions() { // 执行3个函数 Function1(); Function2(); Function3(); } static void Function1() { // 第一个函数的代码 Console.WriteLine("Function 1 is executing..."); Thread.Sleep(1000); } static void Function2() { // 第二个函数的代码 Console.WriteLine("Function 2 is executing..."); Thread.Sleep(2000); } static void Function3() { // 第三个函数的代码 Console.WriteLine("Function 3 is executing..."); Thread.Sleep(3000); } } ``` 这个示例代码中,我们使用Thread类创建了一个新线程,并在该线程执行ExecuteFunctions()函数。ExecuteFunctions()函数会依次调用Function1()、Function2()和Function3()函数。每个函数都会休眠一段时间,模拟函数需要执行的耗时操作。在主线程中,我们启动线程后立即继续执行其他操作,并在新线程执行完毕后等待它结束。最后,我们输出程序执行完毕的信息,程序结束。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值