首页 > 编程语言 > 详细

多线程的同步机制

时间:2020-06-24 21:45:19      阅读:70      评论:0      收藏:0      [点我收藏+]

一、通过synchronized执行一半同步,一半异步

1.新建一个Task.java

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));
           }
        }
    }
}

2.新建Mythread1.java

public class Mythread1 extends Thread{
    private Task task;
    public Mythread1(Task task){
        super();
        this.task=task;
    }
    public void run(){
        super.run();
        task.doLongTimeTask();
    }
}

3.新建Mythread2.java

public class Mythread2 extends Thread{
    private Task task;
    public Mythread2(Task task){
        super();
        this.task=task;
    }
    public void run(){
        super.run();
        task.doLongTimeTask();
    }
}

4.新建run.java

public class Run {
    public static void main(String[] args) throws InterruptedException {
        Task task=new Task();
        Mythread1 t1=new Mythread1(task);
        t1.setName("线程1");
        t1.start();
        Mythread2 t2=new Mythread2(task);
        t2.setName("线程2");
        t2.start();
    }
}

5.输出结果:

技术分享图片

 

 

技术分享图片

 

 我们可看到,程序运行时,同步代码块只能允许一个线程运行,而不能存在多个线程交替运行,必须等待另外一个线程结束才能运行本线程,

在非同步代码块中,线程可以交替运行

 

二、验证synchronized(锁定当前对象)

1.创建Task.java

 

public class Task {
    public synchronized void otherMethod(){
        System.out.println("===============run-otherMethod");
    }
    public void doLongTimeTask(){
        synchronized(this){
           for(int i=0;i<100;i++){
               System.out.println("synchronized threadName="+Thread.currentThread().getName()+" i="+(i+1));
           }
        }
    }
}

2.创建Mythread1.java

public class Mythread1 extends Thread{
    private Task task;
    public Mythread1(Task task){
        super();
        this.task=task;
    }
    public void run(){
        super.run();
        task.doLongTimeTask();
    }
}

3.创建Mythread.java

public class Mythread2 extends Thread{
    private Task task;
    public Mythread2(Task task){
        super();
        this.task=task;
    }
    public void run(){
        super.run();
        task.otherMethod();
    }
}

4.创建Run.java

public class Run {
    public static void main(String[] args) throws InterruptedException {
        Task task=new Task();
        Mythread1 t1=new Mythread1(task);
        t1.setName("线程1");
        t1.start();
        Mythread2 t2=new Mythread2(task);
        t2.setName("线程2");
        t2.start();
    }
}

5.结果

由于创建synchronized(this)是针对对象锁,虽然是不同的对象,但是只拥有一把锁,因此执行同步

 

多线程的同步机制

原文:https://www.cnblogs.com/hkMblogs/p/13189998.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!