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

今天去面试的时候,遇到的笔试题,当时没有想到,回来学习记录下。今天去面试的时候,遇到的笔试题,当时没有想到,回来学习记录下。

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值