【发布时间】:2017-11-04 14:50:22
【问题描述】:
我正在学习java中的同步。今天被下面的示例代码打动了。
在下面的代码中,test() 方法是同步的。所以,我假设 th1 的 test() 调用将完成,然后 th2 的 test() 调用会开始。然而,事情并不是这样发生的。输出交织在一起。你能帮我理解为什么吗?
public class MyThread {
public static void main(String[] args)
{
SampleThread sample = new SampleThread("one");
Thread th = new Thread(sample);
th.start();
SampleThread sample2 = new SampleThread("two");
Thread th2 = new Thread(sample2);
th2.start();
}
}
class SampleThread implements Runnable
{
public SampleThread(String name)
{
this.name=name;
}
String name;
@Override
public void run() {
test();
}
public synchronized void test()
{
for(int j=0;j<10;j++)
{
System.out.println(name + "--" + j );
}
}
}
【问题讨论】:
标签: java multithreading