多线程题目
题目描述
有3个线程和1个公共的字符数组。线程1的功能就是向数组输出A,线程2的功能就是向字符输出l,线程3的功能就是向数组输出i。要求按顺序向数组赋值AliAliAli,Ali的个数由线程函数1的参数指定。
代码
import java.util.ArrayList;
import java.util.List;
/**
* <p>ClassName: ThreadClass </p>
* <p>Description: 多线程</p>
* <p>Author: spring.zhang</p >
* <p>Date: 2020年4月23日</p>
*/
public class ThreadClass {
public static void main(String[] args) {
final Hander hander = new Hander(3);
for (int i = 0; i < 3; i++) {
new Thread(new Runnable() {
@Override
public void run() {
hander.print(Thread.currentThread().getName());
}
}, i + "").start();
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(hander.list.toString());
}
}
class Hander {
private int no;
public Hander(int no) {
this.no = no ;
}
private int status = 0;
List<String> list = new ArrayList<String>();
String arr[] = { "A", "l", "i" };
// 将该方法上锁
public synchronized void print(String threadName) {
for(int i=0; i<no; i++) {
int threadIndex = Integer.parseInt(threadName);
while (threadIndex != status) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
// 添加到数组
list.add(arr[threadIndex]);
// 状态转移
status = (status + 1) % 3;
this.notifyAll();
}
}
}