您的位置:首页 > 职场人生

有三个线程名字分别是A、B、C,每个线程只能打印自己的名字,在屏幕上顺序打印 ABC,打印10次。

2017-03-15 22:23 661 查看
今天去面试的时候,遇到的笔试题,当时没有想到,回来学习记录下。今天去面试的时候,遇到的笔试题,当时没有想到,回来学习记录下。

public class TestPrintOrder {
public static void main(String[] args) {
AtomicInteger atomic = new AtomicInteger();
Print tPrint = new Print();
Thread threadA = new ThreadTest("A", 0, tPrint, 10, atomic);
Thread threadB = new ThreadTest("B", 1, tPrint, 10, atomic);
Thread threadC = new ThreadTest("C", 2, tPrint, 10, atomic);
threadA.start();
threadB.start();
threadC.start();
}
}
class ThreadTest extends Thread{
private String name = "";
private Integer id = 0;
private Print tPrint = null;
private int count = 0;
AtomicInteger atomic = null;
public ThreadTest(String name, Integer id, Print tPrint, int count,
AtomicInteger atomic) {
super();
this.name = name;
this.id = id;
this.tPrint = tPrint;
this.count = count;
this.atomic = atomic;
}
public void run(){
while(count > 0){
if(atomic.get() % 3 == id){
tPrint.printName(name);
count --;
atomic.getAndIncrement();
}
}
}
}
/**
* 打印
*/
class Print{
void printName(String name){
System.out.print(name);
}
}

1.设计上注意,把打印这个对象独立出来,以便控制资源的同步

2.使用atomic类原子性控制线程的执行,此处的取模,相当于一个变量标识

3.如果是打印一遍,使用线程的join(),比较便捷。

public class TestPrintOrder1 {
public static void main(String[] args) throws InterruptedException {
Thread testA = new TestThread("A");
Thread testB = new TestThread("B");
Thread testC = new TestThread("C");
testA.start();
testA.join();
testB.start();
testB.join();
testC.start();
}
}
class TestThread extends Thread{
String name = "";
public TestThread(String name){
this.name = name;
}
public void run(){
System.out.print(name);
}
}


参考文章 :http://blog.csdn.net/seapeak007/article/details/53437339
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  Java 多线程 面试题
相关文章推荐