【发布时间】:2014-12-30 13:00:23
【问题描述】:
我有以下代码:
public class Experimenter implements Runnable
{
private volatile Integer a = new Integer(0);
public Experimenter() throws Exception
{
System.out.println("start");
}
public void funk() throws InterruptedException
{
synchronized (a)
{
System.out.println("in");
Thread.sleep(5000);
System.out.println("out");
}
}
public static void main(String[] args) throws Exception
{
Thread a = new Thread(new Experimenter(), "a");
Thread b = new Thread(new Experimenter(), "b");
Thread c = new Thread(new Experimenter(), "c");
Thread d = new Thread(new Experimenter(), "d");
Thread e = new Thread(new Experimenter(), "e");
a.start();
b.start();
c.start();
d.start();
e.start();
}
@Override
public void run()
{
try
{
funk();
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
我曾预料到,因为一次只有一个线程可以使用同步块,它会打印如下内容,每个输入和输出之间有 5 秒的间隙:
start
start
start
start
start
in
out
in
out
in
out
in
out
in
out
但是,相反,我得到以下信息。所有的输入,5 秒后,所有的输出。:
start
start
start
start
start
in
in
in
in
in
out
out
out
out
out
有人可以帮忙解释一下吗?
【问题讨论】:
标签: java multithreading synchronized