这是我的代码(类):
package table2thread;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Table2Thread extends Thread {
private int j;
private boolean flag;
Table2Thread(int j0) {
j = j0;
}
public void run() {
if (Thread.currentThread().getName().equals("Thread1")) {
for (int i = 1; i < 11; i++) {
System.out.println(j + "*" + i + "=" + j * i);
flag = true;
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Table2Thread.class.getName()).log(Level.SEVERE, null, ex);
}
}
} else if (Thread.currentThread().getName().equals("Thread1") && flag == true) {
for (int i = 1; i < 11; i++) {
System.out.println(j + "*" + i + "=" + j * i);
flag = false;
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
Logger.getLogger(Table2Thread.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
}
}
这是我的主要课程:
public class Main {
public static void main(String[] args) {
Table2Thread a1 =new Table2Thread(3);
a1.setName("Thread1");
a1.start();
Table2Thread a2 =new Table2Thread(4);
a2.setName("Thread2");
a2.start();
}
}
我一次只需要 1 个线程,并且只有一个唯一的线程。首先是a1,然后是a2,然后是a1和a2,但是现在当我运行我的代码时,我会得到重复,例如首先a1开始然后a2然后在3-4增量之后a1开始并且a1再次开始然后a2开始并且再次a2开始。我尝试了很多不同的东西,但由于我是新手,我无法让它工作。
请帮忙