日期:2014-05-18  浏览次数:20743 次

多线程问题,同步后还是没有解决?
class Ticket implements Runnable
{   
private int tk = 100;
public void run()
{
while (true)
{synchronized (new Object())
{
if (tk>0)
{
                                          try
{
Thread.sleep(10);
}
catch (Exception e)
{
}
System.out.println(Thread.currentThread().getName()+"...."+tk--);

}
}
}



}

}

class LockTest 
{
public static void main(String[] args) 
{

Ticket tk = new Ticket();
Thread t1 = new Thread (tk);
Thread t2 = new Thread (tk);
Thread t3 = new Thread (tk);
Thread t4 = new Thread (tk);
t1.start();
t2.start();
t3.start();
t4.start();
}
}
运行结果:
Thread-0....100
Thread-1....99
Thread-2....97
Thread-3....98
Thread-0....96
Thread-1....95
Thread-2....94
Thread-3....93
Thread-0....92
Thread-1....91
Thread-2....90
Thread-3....89
Thread-0....88
Thread-1....87
Thread-2....86
Thread-3....85
Thread-0....84
Thread-1....83
Thread-2....82
Thread-3....81
Thread-0....80
Thread-1....79
Thread-2....78
Thread-3....77
Thread-0....76
Thread-1....75
Thread-2....74
Thread-3....73
Thread-0....72
Thread-1....71
Thread-2....70
Thread-3....69
Thread-0....68
Thread-1....67
Thread-2....66
Thread-3....65
Thread-0....64
Thread-1....63
Thread-2....62
Thread-3....61
Thread-0....60
Thread-1....59
Thread-2....58
Thread-3....57
Thread-0....56
Thread-1....55
Thread-2....54
Thread-3....53
Thread-0....52
Thread-1....51
Thread-2....50
Thread-3....49
Thread-0....48
Thread-1....47
Thread-2....46
Thread-3....45
Thread-0....44
Thread-1....43
Thread-2....42
Thread-3....41
Thread-0....40
Thread-1....39
Thread-2....38
Thread-3....37
Thread-0....36
Thread-1....35
Thread-2....34
Thread-3....33
Thread-0....32
Thread-1....31
Thread-2....30
Thread-3....29
Thread-0....28
Thread-1....27
Thread-2....26
Thread-3....25
Thread-0....24
Thread-1....23
Thread-2....22
Thread-3....21
Thread-0....20
Thread-1....19
Thread-2....18
Thread-3....17
Thread-1....16
Thread-3....14
Thread-2....15
Thread-0....13
Thread-3....12
Thread-1....11
Thread-2....10
Thread-0....9
Thread-3....8
Thread-1....7
Thread-2....6
Thread-0....5
Thread-3....4
Thread-1....3
Thread-2....2
Thread-0....1
Thread-3....0
Thread-1....-1
Thread-2....-2
为什么会出现负值?
多线程 sychronized

------解决方案--------------------
synchronized (new Object())   每次锁的都是new 的 能锁得住吗...