例题:
编写4个线程,第一个线程从1加到25,第二个线程从26加到50,第三个线程从51加到75,第四个线程从76加到100,最后再把四个线程计算的结果相加。
/**
* Created by Intellij IDEA.
* User: specialfinger
* Date: 2021/11/12
*/
public class AddThread extends Thread{
private int begin;
private int end;
private int t;
static int sum=0;
public AddThread(int x,int y){
this.begin=x;
this.end=y;
}
@Override
public void run() {
for (int i=this.begin;i<=this.end;i++){
t+=i;
}
//class对象锁
synchronized (AddThread.class){
//System.out.println(Thread.currentThread().getName()+"----"+t);
sum+=t;
}
}
}
public class Main {
public static void main(String[] args) throws InterruptedException{
for (int i=0;i<4;i++){
AddThread a=new AddThread(i*25+1,(i+1)*25);
a.start();
}
Thread.sleep(500);//计算需要一定时间?
System.out.println(AddThread.sum);
}
}
threadA.join( ):将线程threadA合并到该语句所在的线程2,当线程threadA执行完成后,线程2才能继续执行。
此题第一眼就想到new四个Thread,然后用Runnable join实现同步,我这里参考了这篇文章,对于理解synchronized有很大帮助
深入理解Java并发之synchronized实现原理_zejian的博客-CSDN博客_synchronized底层原理