首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > JAVA > Java相关 >

java 对象锁有关问题

2013-02-04 
java 对象锁问题class PingPong2 { synchronized void hit(long n) { for(int i 1 i 3 i++) System.

java 对象锁问题
class PingPong2 { 
synchronized void hit(long n) { 
for(int i = 1; i < 3; i++) 
System.out.print(n + "-" + i + " "); 


public class Tester implements Runnable { 
 PingPong2 pp2 = new PingPong2(); 
 
public static void main(String[] args) { 
new Thread(new Tester()).start(); 
new Thread(new Tester()).start(); 



public void run() 
{ pp2.hit(Thread.currentThread().getId()); } 
}

答案选项是:
        a)The output could be 5-1 6-1 6-2 5-2
b)The output could be 6-1 6-2 5-1 5-2
c)The output could be 6-1 5-2 6-2 5-1
d)The output could be 6-1 6-2 5-1 7-1
我用双核电脑运行了一下,a) b)都有可能。
我的疑问是:在单核cpu时,既然一个线程获得Pingpong2的对象锁,hit()函数运行完之前,锁不应该释放。运行结果应该是5-1 5-2 6-1 6-2 或者是6-1 6-2 5-1 5-2。会不会出现5-1 6-1 6-2 5-2的情况?
            而对于多核cpu,运行情况有什么不同吗? java thread
[解决办法]
不明白楼主为什么非要强调多核还是单核? 应该结果没区别吧?
5-1 6-1 6-2 5-2 我觉得是可以出现的。
需要注意的是 这个不是STAITC方法他锁的是对象 不是类, 你要注意2个线程他NEW了2个对象, 他们之间应该是不存在数据并发的问题的

热点排行