我已经写了一个代码,创建了几个线程并启动它。我使用同步块锁定了对象上的监视器。我期望创建的第一个线程应该锁定对象并完成它的工作。然后任何其他对象都可以进入它。
但是它没有发生,程序在下面。
class ThreadCreationDemo implements Runnable
{
public void run()
{
synchronized(this)
{
for(int i=0;i<10;i++)
{
System.out.println("i: "+i+" thread: "+Thread.currentThread().getName()+" threadgroup: "+Thread.currentThread().getThreadGroup()+" "+Thread.holdsLock(this));
try {
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e.toString());
}
}
}
}
public static void main(String args[])
{
Thread t[]=new Thread[5];
for(int i=0;i<5;i++)
{
t[i]=new Thread(new ThreadCreationDemo());
t[i].start();
}
}
}我预计结果应该是这样的。
首先,在线程名下打印i=0到9的所有值,比如线程0,然后是线程1,依此类推。
但是输出是这样的:
i: 0 thread: Thread-1
i: 0 thread: Thread-3
i: 0 thread: Thread-2
i: 0 thread: Thread-0
i: 0 thread: Thread-4
i: 1 thread: Thread-1
i: 1 thread: Thread-4
i: 1 thread: Thread-3
i: 1 thread: Thread-0
i: 1 thread: Thread-2
i: 2 thread: Thread-1
i: 2 thread: Thread-3
i: 2 thread: Thread-2
i: 2 thread: Thread-0
i: 2 thread: Thread-4
i: 3 thread: Thread-1
i: 3 thread: Thread-3
i: 3 thread: Thread-0
i: 3 thread: Thread-4
i: 3 thread: Thread-2
i: 4 thread: Thread-1
i: 4 thread: Thread-3
i: 4 thread: Thread-2
i: 4 thread: Thread-4
i: 4 thread: Thread-0
i: 5 thread: Thread-1
i: 5 thread: Thread-4
i: 5 thread: Thread-3发布于 2013-09-22 15:31:22
问题是你每次都在创建新的对象:new ThreadCreationDemo()
因此,所有线程都会在不同的对象上获得锁,因此锁定将失败。
发布于 2013-09-22 15:32:21
您正在同步
synchronized(this)换句话说,每个实例都锁定了自己。您没有锁定共享对象。
一种解决方案是锁定由所有类实例共享的静态对象。例如
synchronized (ThreadCreationDemo.class) {...}或者,在创建Thread时,传入每个Thread都可以同步的共享对象引用。
new ThreadCreationDemo(new Object());
...
public ThreadCreationDemo(Object o) {
this.lock = o
}
public void run () {
synchronized (lock) {
...
}
}https://stackoverflow.com/questions/18941430
复制相似问题