java多线程小问题

来源:百度知道 编辑:UC知道 时间:2024/06/19 20:58:08
如下,程序中我加了线程锁synchronized,可是执行时怎么还是分线程执行呢?这问题出在哪里,知道的告知一下!

public class testxiancheng implements Runnable
{
public static void main(String[] args)
{
testxiancheng s1=new testxiancheng();
Thread s11=new Thread(s1);
testxiancheng s2=new testxiancheng();
Thread s22=new Thread(s2);
s11.start();
s22.start();

}
public void run()
{
test();
}
public synchronized void test()
{
try
{
for (int i=0; i<100;i++ )
{
System.out.println(i);
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}

很显然这个不能同步是因为你执行了 不同 testxiancheng 实例的test() 方法, 这样并不能同步执行,我估计你的本来意思是这样的:

public class testxiancheng implements Runnable {
public static void main(String[] args) {
testxiancheng s1 = new testxiancheng();
Thread s11 = new Thread(s1,"Thread1");
Thread s22 = new Thread(s1,"Thread2");
s11.start();
s22.start();
}

public void run() {
test();
}

public synchronized void test() {
try {
for (int i = 0; i < 100; i++) {
String threadName = Thread.currentThread().getName();
System.out.println(threadName+"=>"+i);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}

没有调用RUN()方法