synchronized修饰方法,保证数据同步准确性,限制线程互斥访问

来源:互联网 发布:软件著作权的源代码 编辑:程序博客网 时间:2024/05/20 04:46
1.未加synchronized关键,造成访问顺序混乱

package thread;/** * @author xiaolong.zhu.baby@qq.com created on 2015/2/6. */public class Test extends Thread {    public void jump() {        for (int i = 0; i < 100; i++) {            if(i%10==0)
System.out.println(); System.out.print(" "+this.currentThread().getName() + ":" + i + "\t"+" "); } } @Override public void run() { jump(); } public static void main(String[] args) { Test test = new Test(); Thread a = new Thread(test, "A"); Thread b = new Thread(test, "B"); a.start(); b.start(); }}
运行结果:



2. 添加synchronized进行互斥访问可以解决数据不同步的问题

package thread;/** * @author xiaolong.zhu.baby@qq.com created on 2015/2/6. */public class Test extends Thread {    public synchronized void jump() {        for (int i = 0; i < 100; i++) {            if(i%10==0)
System.out.println(); System.out.print(" "+this.currentThread().getName() + ":" + i + "\t"+" "); } } @Override public void run() { jump(); } public static void main(String[] args) { Test test = new Test(); Thread a = new Thread(test, "A"); Thread b = new Thread(test, "B"); a.start(); b.start(); }}
运行结果:



总结:使用了synchronized可以使一个线程运行完synchronized所修饰的方法,其他需要排队等候,可以保证数据的准确性。







0 0
原创粉丝点击