编写一个程序,开启3个线程,这3个线程的ID分别为A、B、C,每个线程将自己的ID在屏幕上打印10遍,要求输出结果必须按ABC的顺序显示;如:ABCABC….依次递推。
1、线程未加顺序执行程序
package com.pertops.route;
public class ThreadTemplate {
public static void main(String[] args) {
for(int i=0;i<10;i++){
new Thread(new Runnable() {
@Override
public void run() {
sysThreadName();
}
}, "A").start();
new Thread(new Runnable() {
@Override
public void run() {
sysThreadName();
}
}, "B").start();
new Thread(new Runnable() {
@Override
public void run() {
sysThreadName();
}
}, "C").start();
}
}
static public void sysThreadName(){
System.out.print(Thread.currentThread().getName());
}
}
15280d70649a94fd4915716b1cfeeea.png
当上面这段代码敲完运行后并会发现线程输出时是无序的~换个角度思考一下如何使这些线程按人为所期望的顺序执行呢?
使用线程的join方法,该方法的作用是“等待线程执行结束”,即join()方法后面的代码块都要等待现场执行结束后才能执行
2、线程添加顺序执行程序
package com.pertops.route;
public class ThreadTemplate2 {
public static void main(String[] args) throws InterruptedException {
for(int i=0;i<10;i++){
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
sysThreadName();
}
}, "A");
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
sysThreadName();
}
}, "B");
Thread thread3 = new Thread(new Runnable() {
@Override
public void run() {
sysThreadName();
}
}, "C");
thread1.start();
//thread1.sleep(100);
thread1.join();
thread2.start();
//thread2.sleep(100);
thread2.join();
thread3.start();
thread3.join();
//thread3.sleep(100);
}
}
static public void sysThreadName(){
System.out.print(Thread.currentThread().getName()+"--");
}
}
f34a184a5e78fd5ab4011d388ae58e8.png
网友评论