多线程的问题
class SubThread extends Thread {
public SubThread(String name)
{
super(name);
}
public void run()
{
for(int i = 0; i < 3; i++)
{
System.out.println(Thread.getcurrentThread().getName() + "--" + i);
}
try {Thread.sleep(500);}
catch(Exception e) {}
}
}
public class MainThread
{
public static void main(String[] args)
{
for(int i=0; i < 3; i++)
{
SubThread s=new SubThread();
s.start();
}
}
}
不知道为什么编译不出来 为什么错?
搜索更多相关的解决方案:
线程
----------------解决方案--------------------------------------------------------
SubThread s=new SubThread();
就是你这一句错了,因为你这里用的是无参构造函数
可是你的SubThread定义的时候,却写了一个有参构造函数,当你定义了一个有参构造函数的时候,编译器就不会自动为你配备一个无参构造函数了。
----------------解决方案--------------------------------------------------------
System.out.println(Thread.getcurrentThread().getName() + "--" + i);
那么这句错在哪呢?
----------------解决方案--------------------------------------------------------
在Thread里的方法中,没有getcurrentThread()这个方法
只有Thread.currentThread()这个方法,所以你错了
----------------解决方案--------------------------------------------------------
要是想把他作成同步线程,sychronized怎么放置呢?
----------------解决方案--------------------------------------------------------
放在你想要同步的方法前面
----------------解决方案--------------------------------------------------------
我是放在RUN方法前面 使得RUN方法同步,但不起作用啊!??
class SubThread extends Thread
{
public SubThread(String name)
{
super(name);
}
public synchronized void run()
{
for(int i = 0; i < 3; i++)
{
System.out.println(Thread.currentThread().getName() + "--" + i);
}
}
}
public class MainThread
{
public static void main(String[] args)
{
SubThread s1=new SubThread("hehe");
SubThread s2=new SubThread("lala");
s1.start();
s2.start();
}
}
----------------解决方案--------------------------------------------------------
当然,你怎么会让RUN同步呢,RUN本来就是每个线程用的
你把自己写的方法同步
----------------解决方案--------------------------------------------------------
我想达到的效果是
hehe--0
lala--1
hehe--2
hehe与lala调用RUN方法是同步的,但结果是
hehe--0
hehe--1
hehe--2
lala--0
lala--1
lala--2
Press any key to continue...
错在哪呢?
谢谢千里冰峰
----------------解决方案--------------------------------------------------------
把一个整型变量设为static的
----------------解决方案--------------------------------------------------------