成功的路上总是离不开贵人的帮助,名师的指点和小人的刺激。

莫怕,过了桥,就翻篇了

2.2.4一半异步,一半同步

本例说明:不在同步代码块的是异步执行,在同步代码块时同步的

package com.cky.bean;

/**
 * Created by chenkaiyang on 2017/12/6.
 */
public class ObjectService {
    public void serviceMethodA(){
        for (int i = 0; i < 100; i++) {
            System.out.println("no同步"+ Thread.currentThread().getName() +" i="+(i+1));
        }
        System.out.println("");
        synchronized (this) {
            for (int i = 0; i < 100; i++) {
                System.out.println("同步"+ Thread.currentThread().getName() +" i="+(i+1));
            }
        }

    }

}
package com.cky.thread;

import com.cky.bean.ObjectService;

/**
 * Created by chenkaiyang on 2017/12/5.
 */
public class ThreadA extends Thread{
    private ObjectService service;
    public ThreadA(ObjectService service) {
        super();
        this.service = service;
    }

    @Override
    public void run() {
        super.run();
        service.serviceMethodA();
    }
}
package com.cky.thread;

import com.cky.bean.ObjectService;

/**
 * Created by chenkaiyang on 2017/12/5.
 */
public class ThreadB extends  Thread{
    private ObjectService service;
    public ThreadB(ObjectService service) {
        super();
        this.service = service;
    }

    @Override
    public void run() {
        super.run();
        service.serviceMethodA();
    }
}
package com.cky.test;

import com.cky.bean.ObjectService;
import com.cky.thread.ThreadA;
import com.cky.thread.ThreadB;

/**
 * Created by chenkaiyang on 2017/12/6.
 */
public class Test2 {
    public static void main(String[] args) {
        ObjectService objectService = new ObjectService();
        ThreadA a = new ThreadA(objectService);
        a.setName("a");
        ThreadB b = new ThreadB(objectService);
        b.setName("b");
        a.start();
        b.start();

    }
}
no同步a i=1
no同步b i=1
no同步b i=2
no同步b i=3
no同步b i=4
no同步b i=5
no同步b i=6
no同步b i=7
no同步b i=8
同步b i=1
同步b i=2
同步b i=3
同步b i=4
同步b i=5
同步b i=6
同步b i=7
同步b i=8
同步b i=9
同步b i=10

结果可知:同步代码块的代码是排队执行的,而非同步代码块是异步执行的。

posted on 2017-12-06 22:06  痞子陈2016  阅读(154)  评论(0编辑  收藏  举报

导航