小弟刚学java不久,这是迅雷的那道多线程题。
原题:有三个线程ID分别是A、B、C,请有多线编程实现,在屏幕上循环打印10次ABCABC存在一些问题,求高手帮忙。代码运行时有问题public class SequenceWork { private static Integer abc ;
static int cnt;
public static void main(String[] args) {
int i;
abc=0;cnt=10;
for(i=0;i<cnt;i++){
MyThread mm= new MyThread(i);
mm.start();
}
} static class MyThread extends Thread { //为何得声明为static呢?不声明static好像new不了MyThread的对象。
int Threadid;
MyThread(int i){
Threadid=i;
}
public void run() {
//int Num=3;
while (true) {
synchronized (abc) {
if (abc==Threadid ) {
//Num--;
System.out.print("asdf"+Threadid);
abc=(++abc)%cnt;
abc.notifyAll();
} else {
try {
abc.wait();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
} }
} }
}}
原题:有三个线程ID分别是A、B、C,请有多线编程实现,在屏幕上循环打印10次ABCABC存在一些问题,求高手帮忙。代码运行时有问题public class SequenceWork { private static Integer abc ;
static int cnt;
public static void main(String[] args) {
int i;
abc=0;cnt=10;
for(i=0;i<cnt;i++){
MyThread mm= new MyThread(i);
mm.start();
}
} static class MyThread extends Thread { //为何得声明为static呢?不声明static好像new不了MyThread的对象。
int Threadid;
MyThread(int i){
Threadid=i;
}
public void run() {
//int Num=3;
while (true) {
synchronized (abc) {
if (abc==Threadid ) {
//Num--;
System.out.print("asdf"+Threadid);
abc=(++abc)%cnt;
abc.notifyAll();
} else {
try {
abc.wait();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
} }
} }
}}
PS:上面代码的锁abc应该是对象,不能改变,简单点的改法直接改成abc[]即可。然后就可进行操作了。
我不是高手,不过我知道内部类如果不定义成静态的话就必须new一个外部类的对象,然后通过这个对象来new内部类的对象,而用静态内部类就不用new外部类对象了。
public static void main(String[] args) {
int i;
abc=0;cnt=10;
for(i=0;i <cnt;i++){
SequenceWork sw = new SequenceWork();
MyThread mm = sw.new MyThread(i);
mm.start();
}
}