日期:2014-05-20 浏览次数:20888 次
同步块,示例代码如下:
public void method3(SomeObject so)
{
synchronized(so)
{
//…..
}
}
这时,锁就是so这个对象,谁拿到这个锁谁就可以运行它所控制的那段代码。当有一个明确的对象作为锁时,就可以这样写程序,但当没有明确的对象作为锁,只是想让一段代码同步时,可以创建一个特殊的instance变量(它得是一个对象)来充当锁:
class Foo implements Runnable
{
private byte[] lock = new byte[0]; // 特殊的instance变量
Public void methodA()
{
synchronized(lock) { //… }
}
//…..
}
注:零长度的byte数组对象创建起来将比任何对象都经济――查看编译后的字节码:生成零长度的byte[]对象只需3条操作码,而Object lock
= new Object()则需要7行操作码。
------解决方案--------------------
package Test;
public class TestForSynchronized {
/**
* @param args
*/
public static void main(String[] args) {
final Test test = new Test();
Thread thread1 = new Thread(new Runnable() {
public void run() {
test.test();
}
}, "ta");
Thread thread2 = new Thread(new Runnable() {
public void run() {
test.test();
}
}, "tb");
thread1.start();
thread2.start();
}
}
class Test {
int i = 0;
public void test() {
synchronized ((Integer) i) {//根据你的说法,把int变量i转型为Integer
for (int j=0; j < 6;j++) {
System.out.println("####################################");
System.out.println(Thread.currentThread().getName() + " " + i);
System.out.println("####################################");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
i++;
}
}
}
}