思路:首先是要创建多个线程的方式,这里我们使用实现Runable接口的方式通过for循环批量创建线程。重点是run方法,要判断每个线程打印哪一个数据。线程切换和打印数据的过程都需要保证是一个线程在工作的
public class TestThreadPrint {
private static Object object=new Object();
private static int threadIndex = 0;
private static volatile int count = 0;
public static void main(String[] args) {
List<Integer> collect = Stream.of(1, 2, 3,4,5,6,7,8,9,10).collect(Collectors.toList());
Scanner scanner = new Scanner(System.in);
int n = scanner.nextInt();
for (int i=0;i<n;i++){
new Thread(new MyThread(i,n,collect)).start();
}
}
static class MyThread implements Runnable{
private int thread;
private int threadCount;
private List<Integer> list;
MyThread(int thread,int count,List<Integer> list){
this.thread= thread;
this.threadCount=count;
this.list=list;
}
@Override
public void run() {
while (count < list.size()-1){
if (threadIndex % threadCount == thread){
synchronized (object){
threadIndex ++;
System.out.println(Thread.currentThread().getName() + ":" + list.get(count));
count ++;
}
}
}
}
}
}