3个线程每个线程只能打印自己的名字,在屏幕上顺序打印 ABC,打印10次

public class TeatPrintOrder {
	
	public static void main(String args[]){		
		AtomicInteger atomic = new AtomicInteger();		
		Print p = new Print();
		ThreadTest a = new ThreadTest(p,"A",0,10,atomic);
		ThreadTest b = new ThreadTest(p,"B",1,10,atomic);
		ThreadTest c = new ThreadTest(p,"C",2,10,atomic);
		
		a.start();b.start();c.start();
	}
		
}

class ThreadTest extends Thread{
	String name="";
	Integer id ;
	Print tPrint = null;
	int count;
	AtomicInteger atomic ;
	ThreadTest(Print p,String name,Integer id,int count,AtomicInteger atomic){
		this.name = name ;
		this.id= id ;
		this.tPrint = p ;
		this.count = count ;
		this.atomic= atomic ;
	}
	public void run(){
		while(count>0){
			if((atomic.get() % 3) ==id){
				tPrint.PrintName(name);
				atomic.getAndAdd(1);
				count--;
			}
		}
	}
}

class Print{
	void PrintName(String name){
		System.out.print(name);
	}
}

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

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

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

static class MyThread extends Thread {
    public MyThread (final String name) {
        super (name);
    }

    @Override
    public void run () {
        System.out.print (currentThread ().getName ());
    }
}

private static void printOnceV2 () throws InterruptedException {
    final MyThread threadA = new MyThread ("A");
    final MyThread threadB = new MyThread ("B");
    final MyThread threadC = new MyThread ("C");
    threadA.start ();
    threadA.join ();        // 等待 A 运行完,再开始 B
    threadB.start ();
    threadB.join ();        // 等待 B 运行完,再开始 C
    threadC.start ();
}



更多的实现方法参考:http://blog.csdn.net/zheng0518/article/details/21728355



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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值