编程语言
首页 > 编程语言> > 浅学Java多线程 Thread synchronized

浅学Java多线程 Thread synchronized

作者:互联网

例题:

编写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);
    }
}

此题第一眼就想到new四个Thread,然后用Runnable join实现同步,我这里参考了这篇文章,对于理解synchronized有很大帮助

深入理解Java并发之synchronized实现原理_zejian的博客-CSDN博客_synchronized底层原理

标签:begin,synchronized,int,浅学,private,线程,多线程,public
来源: https://blog.csdn.net/weixin_48411955/article/details/121297243