gpt4 book ai didi

java - 使用 isALive() 或连接方法时出错

转载 作者:行者123 更新时间:2023-11-29 10:16:02 25 4
gpt4 key购买 nike

我正在尝试使用 isALive 和 join 方法,但它抛出一个错误,如找不到符号....请告诉我这个程序中的错误到底在哪里。join 方法的用途是什么。我知道这是等待线程完成,但我想要详细信息。

class newthread1 implements Runnable {
newthread1() {
Thread t = new Thread(this, "FirstThread");
System.out.println("Child Thread:" + t);
t.start();
}

public void run() {
System.out.println("We are in processing for 1st thread");
int p = 1000, t = 3;
double r = 3.5, si;
try {
si = (p * r * t) / 100;
System.out.println("Simple Interest:" + si);
} catch (ArithmeticException e) {
System.out.println("Error:" + e);
}
}
}

class newthread2 implements Runnable {

newthread2() {
Thread t = new Thread(this, "SecondThread");
System.out.println("Child Thread:" + t);
t.start();
}

public void run() {
try {
System.out.println("We are in processing for 2nd thread");
double a, r = 4.3;
int p = 1000, n = 3;
double temp = Math.pow((1 + r / 100), n);
a = temp * p;
System.out.println("Compound interest:" + a);
} catch (ArithmeticException e) {
System.out.println("Error:" + e);
}
}
}

class mainthread {
public static void main(String args[]) {
newthread1 t11 = new newthread1();
new newthread2();
boolean b = t1.t.isAlive();
System.out.println("Thread is alive:" + b);
t1.t.join();
}
}

最佳答案

解决方案 1
将您的主要方法更改为

class mainthread {
public static void main(final String args[]) throws InterruptedException {
Thread thread = new Thread(new newthread1());
newthread1 t11 = new newthread1();
new newthread2();
boolean b = thread.isAlive();
System.out.println("Thread is alive:" + b);
thread.join();
}
}

并运行线程调用thread.start(),创建可运行对象的实例不会自动开始运行。您明确告诉线程开始或停止。

解决方案 2
或者您可以将 Thread 对象 '' 创建为 global variable 并将类更改为

class newthread1 implements Runnable {
public Thread t;

newthread1() {
t = new Thread(this, "FirstThread");
System.out.println("Child Thread:" + t);
t.start();
}

@Override
public void run() {
System.out.println("We are in processing for 1st thread");
int p = 1000, t = 3;
double r = 3.5, si;
try {
si = p * r * t / 100;
System.out.println("Simple Interest:" + si);
} catch (ArithmeticException e) {
System.out.println("Error:" + e);
}
}

public Thread getT() {
return t;
}
}

然后是main方法

class mainthread {
public static void main(final String args[]) throws InterruptedException {
newthread1 t11 = new newthread1();
new newthread2();
boolean b = t11.t.isAlive();
System.out.println("Thread is alive:" + b);
t11.t.join();
}
}

关于java - 使用 isALive() 或连接方法时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17917650/

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