您的位置:首页 > 编程语言 > Java开发

Java synchronized使用的 正确事例和错误事例

2015-12-08 13:56 871 查看
错误事例

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(){
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: