当前位置: 技术问答>java相关
SCJP模拟题 about synchronized
来源: 互联网 发布时间:2015-03-27
本文导语: Here is a partial listing of a class to represent a game board in a networked game. It is desired to prevent collisions due to more than one thread using the addPic method to modify the array of Image references. import java.awt.*; public cl...
Here is a partial listing of a class to represent a game board in a networked game. It is desired to prevent collisions due to more than one thread using the addPic method to modify the array of Image references.
import java.awt.*;
public class Board
{
Image[] pics=new Image[64];
int active=0;
public boolean addPic(Image mg,int pos)
{
//A synchronized(this)
//B synchronized(pics)
//C synchronized(mg)
//D synchronized(active)
{
if (pics[pos]==null)
{
active++;
pics[pos]=mg;
return true;
}
else
{
return false;
}
}
}
}
请在程序的注释处选择所有可以完成题目要求的答案?
我选择的是ABC
答案是AB
请问,为什么C.就不行呢?
import java.awt.*;
public class Board
{
Image[] pics=new Image[64];
int active=0;
public boolean addPic(Image mg,int pos)
{
//A synchronized(this)
//B synchronized(pics)
//C synchronized(mg)
//D synchronized(active)
{
if (pics[pos]==null)
{
active++;
pics[pos]=mg;
return true;
}
else
{
return false;
}
}
}
}
请在程序的注释处选择所有可以完成题目要求的答案?
我选择的是ABC
答案是AB
请问,为什么C.就不行呢?
|
因为mg在你的方法里面根本就不会引起访问冲突,你每次传进来的mg都是独立的,只是名字共用了而已。