Thread(1)

[size=large]代码小例子:[/size]

package com.test;

public class ThreadTest
{
public static void main(String[] args)
{
Thread1 t = new Thread1();
Thread2 t2 = new Thread2();
t.start();
t2.start();
}

}

class Thread1 extends Thread
{

@Override
public void run()
{
for (int i = 0; i < 100; i++)
{

System.out.println("welcome:" + i);
}
}

}

class Thread2 extends Thread
{

@Override
public void run()
{
for (int i = 0; i < 100; i++)
{

System.out.println("hello world:" + i);
}
}

}

`thread1.join();` 是 Java 中用于线程同步的一个方法。它的作用是让当前线程(主线程)等待 `thread1` 执行完毕后再继续执行。 ### 示例代码 以下是一个简单的例子,展示如何使用 `join()` 方法: ```java public class JoinExample { public static void main(String[] args) throws InterruptedException { Thread thread1 = new Thread(() -> { for (int i = 0; i < 5; i++) { System.out.println("Thread 1: " + i); try { Thread.sleep(100); // 让线程休眠100毫秒 } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }); Thread thread2 = new Thread(() -> { for (int i = 0; i < 5; i++) { System.out.println("Thread 2: " + i); try { Thread.sleep(100); // 让线程休眠100毫秒 } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } }); thread1.start(); thread1.join(); // 主线程等待 thread1 执行完毕 thread2.start(); thread2.join(); // 主线程等待 thread2 执行完毕 System.out.println("All threads have finished execution."); } } ``` ### 解释 - **`thread1.start();`** 启动 `thread1` 线程,使其开始执行任务。 - **`thread1.join();`** 当前线程(这里是主线程)会阻塞,直到 `thread1` 执行完毕。这意味着主线程会等待 `thread1` 完成所有操作后,才会继续执行后续代码。 - **`thread2.start();` 和 `thread2.join();`** 类似地,启动 `thread2` 并让主线程等待其完成。 - **输出顺序** 因为使用了 `join()` 方法,所以 `thread1` 的输出会在 `thread2` 之前完成,确保线程按顺序执行。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值