Java synchronized使用的 正确事例和错误事例
2015-12-08 13:56
871 查看
错误事例
正确事例
这两个事例,其实就差一句代码
正确的是这样的, 类的静态方法
public synchronized static int getint(){
错误的是这样的 , 类的非静态方法
public synchronized int getint(){
package com.kunpengku; import java.util.Random; import java.util.Stack; public class Welcome { public static Stack<Integer> abc = new Stack(); public static void main(String[] args) throws Exception { for (int i=0;i<10;i++){ abc.push(i); } //多线程方式二 Q q = new Q(); Q q2 = new Q(); q.start(); q2.start(); } } class Base{ public static Stack<Integer> abc; Base(){ this.abc = Welcome.abc; } public void work(){ int tmp; while(true){ tmp = getint(); if (tmp < 0) break; System.out.println(Thread.currentThread() + String.valueOf(tmp)); } } public synchronized int getint(){ try{ if(!abc.empty()){ Random random = new Random(); Thread.sleep(random.nextInt(1000)); int tmp = abc.pop(); return tmp; } else{ return -1; } }catch(InterruptedException e){ e.printStackTrace(); return -2; } } } class Q extends Thread{ public void run(){ Base b = new Base(); b.work(); } } //错误事例
正确事例
package com.kunpengku; import java.util.Random; import java.util.Stack; public class Welcome { public static Stack<Integer> abc = new Stack(); public static void main(String[] args) throws Exception { for (int i=0;i<10;i++){ abc.push(i); } //多线程方式二 Q q = new Q(); Q q2 = new Q(); q.start(); q2.start(); } } class Base{ public static Stack<Integer> abc; Base(){ this.abc = Welcome.abc; } public void work(){ int tmp; while(true){ tmp = getint(); if (tmp < 0) break; System.out.println(Thread.currentThread() + String.valueOf(tmp)); } } public synchronized static int getint(){ try{ if(!abc.empty()){ Random random = new Random(); Thread.sleep(random.nextInt(1000)); int tmp = abc.pop(); return tmp; } else{ return -1; } }catch(InterruptedException e){ e.printStackTrace(); return -2; } } } class Q extends Thread{ public void run(){ Base b = new Base(); b.work(); } } //正确事例
这两个事例,其实就差一句代码
正确的是这样的, 类的静态方法
public synchronized static int getint(){
错误的是这样的 , 类的非静态方法
public synchronized int getint(){
相关文章推荐
- JAVA-斐波那契数
- Java 5种字符串拼接方式性能比较。
- 关于 MyEclipse 以后能用的上的优化
- <WebLogicServer> <BEA-000386> <Server subsystem failed. Reason: java.lang.NullPointerException
- java中Date与String的相互转化
- JAVA中Prime算法的原理和实现
- eclipse的debug突然模式不能正常运行,但非debug模式却能正常运行
- Java对象初始化详解
- java入门--循环和日期类
- spring声明式事务管理
- java类的封装 继承 多态
- JAVA当中变量什么时候需要初始化?
- Spring:三种实例化bean的方式
- 第二个spring,第三天
- java源码检查工具列表--pmd
- spring scope prototype与singleton区别
- Java基础_04_面向对象
- MyEclipse自动跳入debug模式的解决
- Spring:入门
- Java Base —— 并发