多线程 一个关于Join和synchronized的小例子
发布人:shili8
发布时间:2023-07-12 09:59
阅读次数:47
在Java中,多线程是一种并发编程的方式,它允许程序同时执行多个任务。在多线程编程中,有两个重要的概念:Join和synchronized。本文将通过一个小例子来解释这两个概念的使用。
假设我们有一个任务,需要计算从1到100的所有数字的和。我们可以使用多线程来加快计算的速度。首先,我们创建一个类SumThread,它继承自Thread类,并重写run()方法。
java class SumThread extends Thread { private int start; private int end; private int sum; public SumThread(int start int end) { this.start = start; this.end = end; this.sum = 0; } public int getSum() { return sum; } @Override public void run() { for (int i = start; i <= end; i++) { sum += i; } } }
在主线程中,我们创建两个SumThread实例,并启动它们。
java public class Main { public static void main(String[] args) throws InterruptedException { SumThread thread1 = new SumThread(1 50); SumThread thread2 = new SumThread(51 100); thread1.start(); thread2.start(); thread1.join(); thread2.join(); int totalSum = thread1.getSum() + thread2.getSum(); System.out.println(Total sum: + totalSum); } }
在上面的代码中,我们使用了join()方法来等待两个线程的执行完成。join()方法会阻塞当前线程,直到被调用的线程执行完成。这样,我们可以确保在计算总和之前,两个线程的计算都已经完成。
此外,我们还使用了synchronized关键字来保证多个线程对sum变量的访问是同步的。在SumThread类中,我们使用了一个共享的sum变量来保存计算结果。由于多个线程会同时访问这个变量,我们需要使用synchronized关键字来确保每次只有一个线程可以访问它。
java class SumThread extends Thread { // ... @Override public synchronized void run() { // ... } }
通过使用join()方法和synchronized关键字,我们可以确保多线程的计算是正确的和同步的。
总结:在多线程编程中,Join和synchronized是两个重要的概念。Join方法可以用来等待一个线程的执行完成,而synchronized关键字可以用来保证多个线程对共享变量的访问是同步的。在实际的多线程编程中,我们需要根据具体的需求来选择合适的方式来处理线程之间的交互和共享资源的访问。