synchronized添加在方法上时

不羁岁月 提交于 2020-01-11 05:19:39
/**
 *
 * 总结:当方法上添加synchronized时,只有当当前线程执行完,下一个线程才可以进入执行
 */
public class SychronizedMethod {

    public synchronized void print(){
        System.out.println(Thread.currentThread().getName()+"开始打印");
        try{
            sleep(1000);
        }catch (InterruptedException e){
            e.printStackTrace();
        }
        System.out.println(Thread.currentThread().getName()+"打印结束");
    }

    public static void main(String args[]){
        Test test = new Test();

        Thread t1 = new Thread(test);
        Thread t2 = new Thread(test);
        Thread t3 = new Thread(test);
        Thread t4 = new Thread(test);
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}

class Test implements Runnable{

    SychronizedMethod sychronizedMethod  = new SychronizedMethod();

    public void run(){
        sychronizedMethod.print();
    }
}

在这里插入图片描述

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!