class Saler implements Runnable
{
private int tick = 50;
public boolean state = true;
public void run()
{
if (this.state)
{
//while (true)
//{
synchronized (this)
{
while(true)
{
if (tick > 0)
{
try {Thread.sleep(10);} catch (InterruptedException e){}
System.out.println(">>code.."+this.tick--);
}
}
}
//}
}
else
{
//while (true)
//{
method();
//}
}
}
private synchronized void method()
{
while (true)
{
if (tick > 0)
{
try {Thread.sleep(10);} catch (InterruptedException e){}
System.out.println(">>method.."+this.tick--);
}
}
}
}
class SaleTick
{
public static void main(String[] args)
{
Saler s1= new Saler();
new Thread(s1).start();
try {Thread.sleep(2);} catch (Exception e) {}
s1.state = false;
new Thread(s1).start();
}
}
如上的一段代码,我想练习的是线程中同步的问题,但是使用现在的代码,始终只有一个线程跑起来了,打印如下:
>>code..50
>>code..49
>>code..48
...................
但是如果我采用代码中注释了的while(true)循环,即循环中使用同步代码块,而不是同步代码块中使用循环2个线程均可跑起来。这是什么原因?
------解决方案--------------------
理解一个问题:
private synchronized void method
synchronized (this)
这两种加锁方式加锁的对象都是this对象,而不是类,如果你有两个对象,那么锁就加在不同的地方,看上去就像没有加锁一样