gpt4 book ai didi

java - 通过匿名内部类创建线程

转载 作者:搜寻专家 更新时间:2023-11-01 01:18:06 24 4
gpt4 key购买 nike

我正在开发创建线程的代码,但没有扩展线程类或实现可运行接口(interface),即通过匿名内部类..

public class Mythread3 {
public static void main(String... a) {

Thread th = new Thread() {

public synchronized void run() {
for (int i = 0; i < 20; i++) {
try {
Thread.sleep(1000);

System.out.print(i + "\n" + "..");
} catch (Exception e) {
e.printStackTrace();
}
}

}

};

th.start();
Thread y = new Thread();
y.start();

}
}

现在请告诉我我是否也可以使用相同的方法创建子线程..!!我试过的是......

public class Mythread3 {
public static void main(String... a) {

Thread th = new Thread() {

public synchronized void run() {
for (int i = 0; i < 20; i++) {
try {
Thread.sleep(1000);

System.out.print(i + "\n" + "..");
} catch (Exception e) {
e.printStackTrace();
}
}

}

};

Thread th1 = new Thread() {

public synchronized void run() {
for (int i = 0; i < 20; i++) {
try {
Thread.sleep(1000);

System.out.print(i + "\n" + "..");
} catch (Exception e) {
e.printStackTrace();
}
}

}

};
th.start();
try {
th.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
th1.start();

}
}

但是里面有两个run()方法,我觉得不太实用..请指教..!

最佳答案

 Runnable run = new Runnable() {
public void run() {
try {
for (int i = 0; i < 20; i++) {
Thread.sleep(1000);
System.out.print(i + "\n" + "..");
}

} catch (InterruptedException e) {
System.out.println(" interrupted");
}
}
};
new Thread(run).start();
new Thread(run).start();

在开始第二个之前不要等待一个完成,否则您有三个线程,其中一个一直在运行(在这种情况下,额外的线程毫无意义)

顺便说一句:您的 synchronized 没有做任何有用的事情,但它可能导致线程无法正常运行。


关于java - 通过匿名内部类创建线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10186466/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com