论坛首页 Java企业应用论坛

三个线程循环打印abc十次

浏览 19812 次
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (1)
作者 正文
   发表时间:2011-12-26   最后修改:2011-12-27
朋友问的题,试着写写。也许有其他实现方式,感觉题目应该是考察线程间协作wait和notify所以选择如下方式实现:
补充:可能是表述有误,对不起大家,原题是“有三个线程ID分别是A、B、C,请有多线编程实现,在屏幕上循环打印ABC十次,即:ABCABCABCABCABCABCABCABCABCABCABCABC……”
/**
 * @author my_corner
 * 2011-12-26
 */
public class ThreadPrint {

	/**
	 * @author my_corner
	 * @param 
	 * @return 
	 * @throws InterruptedException 
	 */
	public static void main(String[] args) throws InterruptedException {
		PrintTask task = new PrintTask();
		
		Thread a = new Thread(task);
		a.setName("a");
		Thread b = new Thread(task);
		b.setName("b");
		Thread c = new Thread(task);
		c.setName("c");
		
		a.start();
		b.start();
		c.start();
		
	}

}

class PrintTask implements Runnable{
	private int times = 0;

	/**
	 * 
	 */
	@Override
	public void run() {
		while(times<30){
			synchronized (this) {
				if(times%3==0){
					if("a".equals(Thread.currentThread().getName())){
						System.out.print("a");
						times++;
						this.notifyAll();
					}else{
						try {
							this.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
				if(times%3==1){
					if("b".equals(Thread.currentThread().getName())){
						System.out.print("b");
						times++;
						this.notifyAll();
					}else{
						try {
							this.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
				if(times%3==2){
					if("c".equals(Thread.currentThread().getName())){
						System.out.print("c");
						times++;
						this.notifyAll();
					}else{
						try {
							this.wait();
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					}
				}
			}
		}
	}
	
}
   发表时间:2011-12-26   最后修改:2011-12-26
public class ThreadPrint implements Runnable {

	public void run() {
		for (int i = 0; i < 10; i++) {
			synchronized (this) {
				System.out.println(Thread.currentThread().getName());
			}
			try {
				Thread.sleep(2000l);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		ThreadPrint task = new ThreadPrint();
		Thread a = new Thread(task);
		a.setName("a");
		Thread b = new Thread(task);
		b.setName("b");
		Thread c = new Thread(task);
		c.setName("c");
		a.start();
		b.start();
		c.start();
	}
}

这样会不会好点
0 请登录后投票
   发表时间:2011-12-27  
cgret 写道
public class ThreadPrint implements Runnable {

	public void run() {
		for (int i = 0; i < 10; i++) {
			synchronized (this) {
				System.out.println(Thread.currentThread().getName());
			}
			try {
				Thread.sleep(2000l);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		ThreadPrint task = new ThreadPrint();
		Thread a = new Thread(task);
		a.setName("a");
		Thread b = new Thread(task);
		b.setName("b");
		Thread c = new Thread(task);
		c.setName("c");
		a.start();
		b.start();
		c.start();
	}
}

这样会不会好点


no,多试几次或者换个机器就能试出来了,你这个例子不能保证每次都是abc的顺序。因为不能保证abc顺序的抢到锁。
0 请登录后投票
   发表时间:2011-12-27  
public class OutThread extends Thread{  
	  
    /** 
     * @param args 
     */  
    private final static int maxCount=100;  
    private static boolean[] bool={true,false,false};  
    private int tag;  
    private int count;  
    public OutThread(String ot,int tag){  
        super(ot);  
        this.tag=tag;  
          
    }  
    public static void main(String[] args) throws InterruptedException {  
          
        Thread threadA=new OutThread("A",0);  
        Thread threadB=new OutThread("B",1);  
        Thread threadC=new OutThread("C",2);  
          
        long begin=System.currentTimeMillis();  
        threadA.start();  
  
        threadB.start();  
  
        threadC.start();  
          
        threadA.join();  
  
        threadB.join();  
  
        threadC.join();  
          
        long end=System.currentTimeMillis();  
          
        System.out.println();  
        System.out.println("耗时: "+(end-begin)+"ms");  
    }  
      
    public void run(){  
        try{  
            synchronized (bool) {  
                while(true){  
                    if(bool[this.tag]){  
                        System.out.print(Thread.currentThread().getName());  
                        this.count++;  
                        bool[this.tag]=false;  
                        bool[(this.tag+1)%3]=true;  
                        bool[(this.tag+2)%3]=false;  
                        bool.notifyAll();  
                        if(count==maxCount)  
                            return;  
                          
                    }else{  
                        bool.wait();  
                    }  
                }  
            }  
        }catch(Exception e){  
            e.printStackTrace();  
        }  
          
    }  
  
} 
0 请登录后投票
   发表时间:2011-12-27  
哦,这样啊,不过我没看到你说需要abc要有顺序的打印
0 请登录后投票
   发表时间:2011-12-27  
神之小丑 写道
public class OutThread extends Thread{  
	  
    /** 
     * @param args 
     */  
    private final static int maxCount=100;  
    private static boolean[] bool={true,false,false};  
    private int tag;  
    private int count;  
    public OutThread(String ot,int tag){  
        super(ot);  
        this.tag=tag;  
          
    }  
    public static void main(String[] args) throws InterruptedException {  
          
        Thread threadA=new OutThread("A",0);  
        Thread threadB=new OutThread("B",1);  
        Thread threadC=new OutThread("C",2);  
          
        long begin=System.currentTimeMillis();  
        threadA.start();  
  
        threadB.start();  
  
        threadC.start();  
          
        threadA.join();  
  
        threadB.join();  
  
        threadC.join();  
          
        long end=System.currentTimeMillis();  
          
        System.out.println();  
        System.out.println("耗时: "+(end-begin)+"ms");  
    }  
      
    public void run(){  
        try{  
            synchronized (bool) {  
                while(true){  
                    if(bool[this.tag]){  
                        System.out.print(Thread.currentThread().getName());  
                        this.count++;  
                        bool[this.tag]=false;  
                        bool[(this.tag+1)%3]=true;  
                        bool[(this.tag+2)%3]=false;  
                        bool.notifyAll();  
                        if(count==maxCount)  
                            return;  
                          
                    }else{  
                        bool.wait();  
                    }  
                }  
            }  
        }catch(Exception e){  
            e.printStackTrace();  
        }  
          
    }  
  
} 

比我写的好
0 请登录后投票
   发表时间:2011-12-27  
华为的2011面试题a卷就有这个,我去过!!!
0 请登录后投票
   发表时间:2011-12-27  
	/**
	 * @param args
	 */
	public static void main(String[] args) {
		final AtomicInteger ai = new AtomicInteger(0);

		Thread a = new Thread("a") {

			private int i = 0;

			@Override
			public void run() {
				while (true) {
					if (ai.get() == 1) {
						System.out.println("a");
						ai.set(2);
						if (i++ == 10) {
							break;
						}
					}
				}
			}
		};
		a.start();

		Thread b = new Thread("b") {
			private int i = 0;

			@Override
			public void run() {
				while (true) {
					if (ai.get() == 2) {
						System.out.println("b");
						ai.set(3);
						if (i++ == 10) {
							break;
						}
					}
				}
			}
		};
		b.start();

		Thread c = new Thread("c") {
			private int i = 0;

			@Override
			public void run() {
				while (true) {
					if (ai.get() == 3) {
						System.out.println("c");
						ai.set(1);
						if (i++ == 10) {
							break;
						}
					}
				}
			}
		};
		c.start();

		ai.set(1);

	}


这样应该可以吧
0 请登录后投票
   发表时间:2011-12-27  
aiheng1988 写道
华为的2011面试题a卷就有这个,我去过!!!

你答的好吗
0 请登录后投票
   发表时间:2011-12-27  
my_corner 写道
cgret 写道
public class ThreadPrint implements Runnable {

	public void run() {
		for (int i = 0; i < 10; i++) {
			synchronized (this) {
				System.out.println(Thread.currentThread().getName());
			}
			try {
				Thread.sleep(2000l);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}

	public static void main(String[] args) {
		ThreadPrint task = new ThreadPrint();
		Thread a = new Thread(task);
		a.setName("a");
		Thread b = new Thread(task);
		b.setName("b");
		Thread c = new Thread(task);
		c.setName("c");
		a.start();
		b.start();
		c.start();
	}
}

这样会不会好点


no,多试几次或者换个机器就能试出来了,你这个例子不能保证每次都是abc的顺序。因为不能保证abc顺序的抢到锁。

多线程不是用来解决不需要按照顺序执行的任务吗,为什么要保证顺序
0 请登录后投票
论坛首页 Java企业应用版

跳转论坛:
Global site tag (gtag.js) - Google Analytics