码迷,mamicode.com
首页 > 其他好文 > 详细

2.2.4一半异步,一半同步

时间:2017-12-07 00:31:41      阅读:165      评论:0      收藏:0      [点我收藏+]

标签:i+1   span   []   cts   end   ted   system   out   public   

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

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

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

2.2.4一半异步,一半同步

标签:i+1   span   []   cts   end   ted   system   out   public   

原文地址:http://www.cnblogs.com/edison20161121/p/7989482.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!