并发编程

自闭症网瘾萝莉.ら 提交于 2020-02-09 10:20:13

Synchronized 修饰类中的静态方法,与非静态方法。

话不多说直接上代码

1234567891011121314151617181920212223242526272829303132333435363738394041
public class MultiThread{    private static int num=0;        public synchronized void printNum(String tag){        try{            if(tag.equals("a")){                                num=100;                System.out.println("tag a,set num over");                Thread.sleep(1000);            }else{                num=200;                System.out.println("tag b,set num over");            }            System.out.println("tag"+tag+",num="+num);        }catch(InterruptedException e){            e.printStackTrace();        }    }        public static void main(String[] args){        final MultiThread m1=new MultiThread();        final MultiThread m2=new MultiThread();                Thread t1=new Thread(new Runnable(){            public void run(){                m1.printNum("a");            } 大专栏  并发编程        });                Thread t2=new Thread(new Runnable(){            public void run(){                m2.printNum("b");            }        });                t1.start();        t2.start();    }}

程序输出的结果:

1234
tag a,set num overtag b,set num overtagb,num=200taga,num=200

其实此时程序会出现两种结果的输出:

1234
tag b,set num overtag a,set num overtagb,num=100taga,num=100

1234
tag b,set num overtag a,set num overtagb,num=200taga,num=200

这是因为int num 被static 修饰,当线程t1和t2的执行顺序不同的时候就会出现这两种结果。此时synchronized是否修饰都不影响程序的执行效果,去掉static 关键字再来观察。

1234
tag a,set num overtag b,set num overtagb,num=200taga,num=100

两次输出的结果并不相同,各自输出了各自的预期输出值。线程之间并没有受到干扰。再synchronzied关键字前加上static ,这样便成为了类锁,整个他t1,t2中的printnum方法会存在抢占,会先执行完其一,再执行另一个,看输出结果。

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