题目1
创建3个线程,让3个线程分别按着顺序打印AAAA,BBBB,CCCC(第一个线程打印AAAA,第二个线程打印BBBB,第一个线程始终在第二个线程之前打印)
代码(该代码为打印3个线程分别打印一次)
public class JoinTest {
public static void main(String[] args) {
Thread prev = Thread.currentThread();
String[] array = {"AAAA","BBBBB","CCCC"};
for(int i = 0;i<3;i++){
Thread thread = new Thread(new MyThread(prev,array[i]),"Thread"+i);
thread.start();
prev = thread;
}
}
}
class MyThread implements Runnable{
private Thread thread;
private String print;
public MyThread(Thread thread,String print){
this.thread = thread;
this.print = print;
}
@Override
public void run() {
try {
thread.join();
for(int i = 0;i<3;i++){
System.out.println(print);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
}
运行结果
AAAA
AAAA
AAAA
Thread0
BBBB
BBBB
BBBB
Thread1
CCCC
CCCC
CCCC
Thread2
题目1 扩展
只创建3个线程,循环打印 题目1 的字符串,并且按照上题中的线程顺序打印