假设我有2个螺纹T1和T2执行可行。我在T1和T2中写了一些东西。在执行T2 3行后,T1应完成其执行,然后将T2完成执行。我可以用 Join()
吗?
我开始编码某些内容,但不确定如何做。
public class JoinTest {
static int count = 0;
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for(int i =0; i< 10 ; i++) {
// System.out.println(i);
count++;
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for(int i =0; i< 10 ; i++) {
// System.out.println(i);
count++;
}
}
});
t1.start();
t2.start();
System.out.println(count);
}
}
只需在T2的run()
方法中调用t1.join()
,就像:
public class JoinTest {
static int count = 0;
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
for(int i =0; i< 10 ; i++) {
// System.out.println(i);
count++;
}
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
for(int i =0; i< 10 ; i++) {
// System.out.println(i);
if (i == 2) { //call t1.join() here, you can change this condition based on your logic
t1.join();
}
count++;
}
}
});
t1.start();
t2.start();
System.out.println(count);
}
}
java multithreading