public class xc6 implements Runnable
{ time tt=new time();
public static void main(String args[])
{ Thread t1=new Thread(new xc6());
Thread t2=new Thread(new xc6());
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}public void run()
{
tt.add(Thread.currentThread().getName());
}}class time
{ private static int m=0;public void add(String s)
{ synchronized(this){
m++;
System.out.println(m);
try
{
Thread.sleep(1);
}
catch(InterruptedException e)
{}
System.out.println("你是第"+m+"个"+s+"的线程");
}
}} 请问那里错了吗?
他输出是
2 t1
2 t2
{ time tt=new time();
public static void main(String args[])
{ Thread t1=new Thread(new xc6());
Thread t2=new Thread(new xc6());
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}public void run()
{
tt.add(Thread.currentThread().getName());
}}class time
{ private static int m=0;public void add(String s)
{ synchronized(this){
m++;
System.out.println(m);
try
{
Thread.sleep(1);
}
catch(InterruptedException e)
{}
System.out.println("你是第"+m+"个"+s+"的线程");
}
}} 请问那里错了吗?
他输出是
2 t1
2 t2
至于这里的 synchronized(this),我觉得并没有起到作用,因为没有缩住m
Thread t2=new Thread(new xc6());
LZ你这里创建了两个线程但并没有共享time对象 ,所以才会输出
1
2
你是第2个t1的线程
你是第2个t2的线程
你只要new一个runnable就行了
因为你为每个runnable都创建了time对象
另外
把time tt=new time(); 这句改成
static time tt=new time(); 也许就可以了