对象及变量的并发访问-----synchronized同步(5)-----synchronized代码块 一半异步 一半同步

 一、synchronized块中的代码是同步执行,synchronized外的则是异步

  先写一个Task类,里面一个方法里面两个代码块,分别同步和不同步

package entity;

/**
 * Created by zhc on 2017/10/10
 */
public class Task {
    public void doLongTimeTask(){
        for (int i = 0; i < 100; i++) {
            System.out.println("nosynchronized threadname = "+Thread.currentThread().getName()+" i =" + (i+1));
        }
        System.out.println("");
        synchronized(this){
            for (int i = 0; i < 100; i++) {
                System.out.println("synchronized threadname = "+Thread.currentThread().getName()+" i =" + (i+1));

            }
        }
    }

}

  两个进程分别调用task对象

  

package extthread;

import entity.Task;

/**
 * Created by zhc on 2017/10/10
 */
public class ThreadF extends Thread{
    private Task task;

    public ThreadF(Task task){
        super();
        this.task = task;
    }

    @Override
    public void run() {
        super.run();
        task.doLongTimeTask();
    }
}
package extthread;

import entity.Task;

/**
 * Created by zhc on 2017/10/10
 */
public class ThreadG extends Thread {
    private Task task;

    public ThreadG(Task task){
        super();
        this.task = task;
    }

    @Override
    public void run() {
        super.run();
        task.doLongTimeTask();
    }
}

  run

package test;

import entity.Task;
import extthread.ThreadF;
import extthread.ThreadG;

/**
 * Created by zhc on 2017/10/10
 */
public class Run5 {
    public static void main(String[] args) {
        Task task = new Task();
        ThreadF t1 = new ThreadF(task);
        t1.start();
        ThreadG t2 = new ThreadG(task);
        t2.start();
    }
}

  结果如下:

  nosynchronized threadname = Thread-0 i =67
  nosynchronized threadname = Thread-1 i =53
  nosynchronized threadname = Thread-0 i =68
  nosynchronized threadname = Thread-1 i =54
  nosynchronized threadname = Thread-1 i =55
  nosynchronized threadname = Thread-1 i =56
  nosynchronized threadname = Thread-1 i =57
  nosynchronized threadname = Thread-0 i =69
  nosynchronized threadname = Thread-1 i =58

  synchronized的两个方法都是同步的

 

二、synchronized(this) 是锁定当前对象的,我们还可以使用其他的对象来作为对象监视器

  synchronized(x){}             //x是非this对象

  可以得到下面三个结论:

  (1)当多个线程执行synchronized(x){}同步代码块的时候呈现同步效果

  (2)当其他线程执行x对象中synchronized同步方法时也是呈现同步效果

  (3)当其他的县城执行x对象中synchronized(this)代码块时也呈现同步效果

  attention:其他线程调用不加synchronized的方法时还是异步             

  

posted on 2017-10-10 15:20  汉成  阅读(353)  评论(0)    收藏  举报

导航