class xt{ public static void main(String in[]){
Thread t1=new Thread(new l());
Thread t2=new Thread(new l());
t1.setName("this");
t2.setName("that"); t1.start();
t2.start();
}
}class l implements Runnable{
public void run(){
tt();
} synchronized void tt(){
int i=0;
for(i=1; i<4; i++){
System.out.print("#"+Thread.currentThread().getName()+" "+i);
if(i==3) System.out.print("\n");
}
}
}我期望的结果是:
#this 1#this 2#this 3
#that 1#that 2#that 3但实际却打成了一排,
哪里错了?
Thread t1=new Thread(new l());
Thread t2=new Thread(new l());
t1.setName("this");
t2.setName("that"); t1.start();
t2.start();
}
}class l implements Runnable{
public void run(){
tt();
} synchronized void tt(){
int i=0;
for(i=1; i<4; i++){
System.out.print("#"+Thread.currentThread().getName()+" "+i);
if(i==3) System.out.print("\n");
}
}
}我期望的结果是:
#this 1#this 2#this 3
#that 1#that 2#that 3但实际却打成了一排,
哪里错了?
我这边运行你的代码是你期望的效果啊
#this 1#this 2#this 3
#that 1#that 2#that 3
不会吧,我运行出来是这样的:#this 1#that 1#this 2#that 2#this 3#that 3
到底怎么回事?
请问我这个代码有没有问题,哪个大侠帮忙看看
synchronized void tt(){这个是实例一级的同步,也就是如果多个线程使用一个实例,才有效,比如
l ll = new l();
Thread t1=new Thread(ll);
Thread t2=new Thread(ll);
否则,每个线程使用各自独立的实例,不存在什么同步问题。
你自己再试试吧。
加油!
public class T{
public static void main(String in[])throws Exception{
Thread t1=new Thread(new l());
Thread t2=new Thread(new l());
t1.setName("this");
t2.setName("that");
t1.start();
t1.sleep(2000);
t2.start();
}
}class l implements Runnable{
public void run(){
tt();
}
synchronized void tt(){
int i=0;
for(i=1; i<4; i++){
System.out.print("#"+Thread.currentThread().getName()+" "+i + " ");
if(i==3) System.out.print("\n");
}
}
}
感谢 l ll = new l();
Thread t1=new Thread(ll);
Thread t2=new Thread(ll);