synchronized+线程池使用案例

本次案例先创建一个类demo,demo内有一个synchronized修饰的void方法输出hello world后面跟上类中的整形数i,然后写一个线程handle实现Runable接口,并使用main函数中定义的demo实例demo2对demo2里面的整形数进行+操作,然后创建一个线程池每次往这个线程池里面添加一个handle的线程对demo2中的i进行处理使用for循环操作十次来验证是否多线程会改变i的值。代码如下:

package study.serialization;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Auther opprash
 * @Date 2018\8\6 0006 2:51
 */
class demo {
    int i=0;
    public synchronized  void doSth(){
        System.out.println("hello world "+i+" ");
        i++;
    }
    public void doSth1(){
        synchronized (SynchronizedDemo.class){
            System.out.println("hello world");
        }

    }
public class SynchronizedDemo {
    }
    public static void main(String [] arg){
        ExecutorService exc=Executors.newCachedThreadPool();
        demo demo2=new demo();
        for(int i=0;i<10;i++)
        {
            exc.execute(new Handle(String.valueOf(i),demo2));


        }
        exc.shutdown();
    }
}
class Handle implements Runnable {
    private String name;
    demo demo2=new demo();
    public Handle(String name,demo demo3) {
        this.name = name;
        this.demo2=demo3;
    }

    @Override
    public void run() {
        System.out.println(name + "Start.Time=" + new Date());
        deil(demo2);
        processCommand();
        ret(this.demo2);
        System.out.println(name + "End.Time=" + new Date());
    }
    public void deil(demo demo1){
        demo1.doSth();
    }
    public demo ret(demo demo4){
        return this.demo2;
    }
    private void processCommand() {
        try {
            Thread.sleep(1000);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String toString() {
        return this.name;
    }
}

猜你喜欢

转载自blog.csdn.net/qq_30675777/article/details/81453213