|
[笔记]看到baoxiong兄的线程笔记,想起一道面试题~~
题目:主线程生成一个5~10的随机数字,然后产生10个子线程,每个子线程每间隔1秒钟输出一个1~10的随机数字。主线程产生的随机数间隔一秒倒数减1,当主线程倒数为0结束,则关闭所有的子线程。
代码:
import java.util.Vector;
public class ThreadTest extends Thread {
private Vector ThreadPool = new Vector();
public synchronized void run() {
// 生成随机数(上限-下限)*Math.random()+下限
int count = (int) ((10 - 5) * Math.random() + 5);
System.out.println("主线程循环次数 : " + count);
// 创建10个子线程
this.createSubThread(10);
// 当主线程结束则10个子线程也结束
while (count > 0) {
try {
System.out.println("倒数 "+count);
sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
count--;
}
for (int j = 0; j < ThreadPool.size(); j++) {
subThread sub = (subThread) ThreadPool.get(j);
//设置标记,如果为false则子线程退出。
sub.setFlag(false);
}
}
//创建子线程
public void createSubThread(int size) {
subThread sub = null;
if (size > 0) {
for (int i = 0; i < size; i++) {
sub = new subThread(String.valueOf(i+1));
ThreadPool.add(sub);
sub.start();
}
}
}
public static void main(String[] args) {
ThreadTest myTest = new ThreadTest();
myTest.run();
}
}
class subThread extends Thread {
private boolean flag = true;
public subThread(String num) {
this.setName("线程 " + num);
}
public void run() {
try {
System.out.println(this.getName() + " 开始... ");
while (flag) {
sleep(1000);
// 产生1-10的随机数
System.out.println(this.getName() + " 随机数: "
+ (int) ((10 - 1) * Math.random() + 1));
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("子线程 "+this.getName() + " 结束! ");
}
public void setFlag(boolean flag) {
this.flag = flag;
}
} |
|