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 ();
}