多线程直接继承Thread类方式设计一个线程例子,在例子中构造4个线程对象实现对同一数据类对象进行操作

多线程直接继承Thread类方式设计一个线程例子,在例子中构造4个线程对象实现对同一数据类对象进行操作(数据初始值为0),其中线程对象1对数据执行+10的操作,线程对象2对数据执行+20的操作, 对象3对数据执行乘以3的操作,线程对象4对数据执行除以4的操作,请考虑线程同步,保证数据操作的正确性。请提供程序代码以及运行结果截图

https://blog.csdn.net/sd_zhangzheng/article/details/51932426

private volatile static int num = 0;
public static void main(String[] args) {
final CyclicBarrier ot2 = new CyclicBarrier(2);
final CyclicBarrier ot3 = new CyclicBarrier(2);
final CyclicBarrier ot4 = new CyclicBarrier(2);
Thread add10 = new Thread(new Runnable() {
public void run() {
try {
num += 10;
System.out.println(num);
ot2.await();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (BrokenBarrierException e) {
e.printStackTrace();
}

        }
    });

    Thread add20 = new Thread(new Runnable() {
        public void run() {
            try {
                ot2.await();
                num += 20;
                System.out.println(num);
                ot3.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    });

    Thread multi3 = new Thread(new Runnable() {
        public void run() {
            try {
                ot3.await();
                num *= 3;
                System.out.println(num);
                ot4.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    });

    Thread devide4 = new Thread(new Runnable() {
        public void run() {
            try {
                ot4.await();
                num /= 4;
                System.out.println(num);
            } catch (InterruptedException e) {
                e.printStackTrace();
            } catch (BrokenBarrierException e) {
                e.printStackTrace();
            }
        }
    });




    devide4.start();
    multi3.start();
    add20.start();
    add10.start();
    try {
        devide4.join();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    System.out.println(num);
}


    ![运行结果](https://img-ask.csdn.net/upload/201903/31/1554007139_995881.png)