public class ThreadDemo {
public static void main(String[] args) {
SubThread threadA = new SubThread();
threadA.setName("A线程");
SubThread threadB = new SubThread();
threadB.setName("B线程");
threadA.start();
threadB.start();
}
static class SubThread extends Thread {
@Override
public void run() {
int num = 0;
for (int i = 1; i <= 5; i++) {
num += new Random().nextInt(10);
System.out.println(this.getName() + &#34;在&#34; + i + &#34;时的累加和为&#34; + num);
}
}
}
}运行结果:
A线程在1时的累加和为0
B线程在1时的累加和为9
A线程在2时的累加和为6
B线程在2时的累加和为9
A线程在3时的累加和为8
B线程在3时的累加和为9
A线程在4时的累加和为15
B线程在4时的累加和为11
A线程在5时的累加和为19
B线程在5时的累加和为11说明:
public class ThreadDemo {
public static void main(String[] args) {
Thread threadA = new Thread(new SubThread());
threadA.setName(&#34;A线程&#34;);
Thread threadB = new Thread(new SubThread());
threadB.setName(&#34;B线程&#34;);
threadA.start();
threadB.start();
}
static class SubThread implements Runnable {
@Override
public void run() {
int num = 0;
for (int i = 1; i <= 5; i++) {
num += new Random().nextInt(10);
System.out.println(Thread.currentThread().getName() + &#34;在&#34; + i + &#34;时的累加和为&#34; + num);
}
}
}
}运行结果:
A线程在1时的累加和为5
B线程在1时的累加和为8
A线程在2时的累加和为14
B线程在2时的累加和为17
A线程在3时的累加和为20
B线程在3时的累加和为17
A线程在4时的累加和为28
B线程在4时的累加和为18
A线程在5时的累加和为29
B线程在5时的累加和为21说明: