一个java多线程编写中的小问题!请大家帮助呀,谢谢了!

2025-02-27 16:15:12
推荐回答(6个)
回答1:

///有个小错误~~~改好了

public class ThreadTest {
public static void main(String[] args) {
Hello t1=new Hello();
Hello t2=new Hello();
t1.start();
t2.start();
}
static class Hello extends Thread{

int i;
public void run(){
while(true){
if(i==5)
break;
System.out.println("Hello"+i++);
try{
Thread.sleep(1000);
} catch (Exception e){
System.out.println("ERROR!");
}

}
}
}
}

回答2:

class Hello extends Thread{
int i;
public void run(){
while(true){
System.out.print("Hello"+i++);
if(i==5)
break;
}
}
}

public class tset_2 {
public static void main(String[] args) {
Hello t1=new Hello();
Hello t2=new Hello();
t1.start();
t2.start();
}

}

回答3:

class ThreadTest {

public static void main(String[] args) {
Hello t1 = new Hello();
Hello t2 = new Hello();
t1.start();
t2.start();
}

static class Hello extends Thread {

int i;

public void run() {
while (true) {
System.out.print("Hello" + i++);
if (i == 5) {
break;
}
}
}
}
}
主函数只能调用静态方法,不是什么内部类的问题,静态类就好了。

回答4:

内部类不能直接访问,要初始化,有两种改的方法,
1.把最下面四个括号改为三个,剩下一个移动到t2.stat() }}

2.直接给Hello t1 = new ThreadTest().new Hello();
Hello t2 = new ThreadTest().new Hello();

回答5:

我给你改了一下,hello是内部内,你的创建hello对象的时候
应该是Hello t1 = new ThreadTest().new Hello();
改成这样:
public class ThreadTest {
public static void main(String[] args) {
ThreadTest test = new ThreadTest();
Hello t1 = test.new Hello();
Hello t2 = test.new Hello();
t1.start();
t2.start();
}

class Hello extends Thread {

int i;

public void run() {
while (true) {
System.out.print("Hello" + i++);
if (i == 5)
break;
}
}
}
}

回答6:

public class ThreadTest {
public static void main(String[] args) {
Hello t1=new Hello();
Hello t2=new Hello();
t1.start();
t2.start();
}
class Hello extends Thread{

int i; // i = 0;
public void run(){
while(true){
System.out.print("Hello"+i++);
if(i==5)
break;
}
}
}
}