代码如下:
package com;
public class method {
private static method m = null;
private static byte[] b = new byte[0];
private method(){
}
public static method getInstance(){
if(m==null){
m = new method();
}
return m;
}
public void print1(){
synchronized (b) {
for(int i = 0;i<1220;i++){
System.out.println(Thread.currentThread().getName()+i);
}
}
}
public void print2(){
synchronized (b) {
for(int i = 0;i<1220;i++){
System.out.println(Thread.currentThread().getName()+i);
}
}
}
}
package com;
public class test {
public static void main(String[] args) {
test t=new test();
t.init();
}
public void init(){
Runnable r = new thread1();
Thread t = new Thread(r,"A");
t.start();
Runnable r1 = new thread2();
Thread t1 = new Thread(r,"B");
t1.start();
}
public class thread1 implements Runnable{
public void run() {
method m = method.getInstance();
m.print1();
}
}
public class thread2 implements Runnable{
public void run() {
method m = method.getInstance();
m.print2();
}
}
}
问题:
如若synchronized (b)中的b是static 则执行的结果是AB按顺序出现,若b是非static则AB交替出现,若b换成thisAB也是交替出现。谁能给我解释下为什么吗,method类中的两个方法里的锁不是指向同一个对象吗。谢谢
哦 那我没仔细看。。。
你在public static method getInstance()这个函数前加synchronized,这样才保证是singleton,只有一个m
[code="java"]public synchronized static method getInstance()[/code]
synchronized锁的是对象,这个楼主应该明白的吧
b是static的话thread1 thread2里面 method m = method.getInstance(); 返回的m里是同一个b啊
不是static的话 m里各有一个b啊,所以运行print1,print2的时候 锁的就不是同一个了啊
另外 线程交替执行貌似也是正常的 因为如果不手动控制,线程本身就不一定是顺序执行的