李敏  
日历
<2024年5月>
2829301234
567891011
12131415161718
19202122232425
2627282930311
2345678
统计
  • 随笔 - 1
  • 文章 - 40
  • 评论 - 4
  • 引用 - 0

导航

常用链接

留言簿(1)

文章分类

文章档案

相册

收藏夹

它山之石

聚贤庄

搜索

  •  

最新评论

 

 

/**
 * 有三个线程ID分别是A、B、C,请用多线编程实现,在屏幕上循环打印10次ABCABC…。
 * 
 
*/

public class TestThread {

    
private void service() {
        
int IDChartCount = ID.values().length - 1;

        IDChart dpool 
= new IDChart(IDChartCount);

        
for (ID id : ID.values()) {
            Thread t 
= new ThreadImpl(dpool, id, id.name());

            t.start();
        }

    }


    
public static void main(String[] args) {
        
new TestThread().service();
    }

}


enum ID {
    a, b, c
}


class ThreadImpl extends Thread {
    
private final ID id;

    
private final IDChart chart;

    
public ThreadImpl(IDChart chart, ID id, String name) {
        
super(name);

        
this.chart = chart;

        
this.id = id;
    }


    
public void run() {
        
for (int i = 0; i < 10;) {
            
synchronized (chart) {
                
if (chart.check(id)) {
                    System.out.println(getId() 
+ " " + getName() + "  " + id);

                    i
++;
                }

            }

            
try {
                sleep(
1);
            }
 catch (InterruptedException e) {
                
// TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

    }

}


class IDChart {
    
private int index = 0;

    
private final int count;

    
public IDChart(int count) {
        
this.count = count;
    }


    
public boolean check(ID id) {
        
if (index == id.ordinal()) {

            
if (index != count)
                index
++;
            
else
                index 
= 0;

            
return true;
        }

        
return false;
    }

}


迅雷面试题以上为我的其中一道题的个人实现
http://www.javaeye.com/topic/534019
posted on 2009-12-02 06:34 李敏 阅读(366) 评论(0)  编辑  收藏 所属分类: 算法

只有注册用户登录后才能发表评论。


网站导航:
 
 
Copyright © 李敏 Powered by: 博客园 模板提供:沪江博客