请大神帮我写个实例,要的效果是:写两个线程,交替打印数字和字母。
谢谢

解决方案 »

  1.   

    public static void main(String[] args) {
    // TODO Auto-generated method stub
    ExecutorService service = Executors.newFixedThreadPool(2);
    service.execute(new Runnable() { @Override
    public void run() {
    // TODO Auto-generated method stub
    int i = 0;
    for (; i < 26; i++) {
    System.out.println(i);
    Thread.yield();
    }
    }
    });
    service.execute(new Runnable() {
    char[] cs = new char[] { 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h',
    'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't',
    'u', 'v', 'w', 'x', 'y', 'z' }; @Override
    public void run() {
    // TODO Auto-generated method stub
    int i = 0;
    for (; i < 26; i++) {
    System.out.println(cs[i]);
    Thread.yield();
    }
    }
    }); }
      

  2.   

    看看这个笨的:public class AlphaAndNumber
    {
    public static void main(String[] args)
    {
    Out o=new Out(); //用于线程同步.
    AlphaOut an=new AlphaOut(o); //输出字母,'a'--'z'循环输出。
    NumberOut num=new NumberOut(o); //输出数字,1--100循环输出。

    new Thread(an).start();
    new Thread(num).start();

    }
    }
    class AlphaOut implements Runnable
    {
    private Out o;
    char c='z';
    public AlphaOut(Out o)
    {
    this.o = o;
    }
    public void run()
    {
    while(true)
    {
    try
    {
    Thread.sleep(1000);
    }
    catch(InterruptedException e)
    {
    e.printStackTrace();
    }
    synchronized(o) 
    {
    while(o.getFlag())
    {
    try
    {
    o.wait();
    }
    catch(InterruptedException ie)
    {
    ie.printStackTrace();
    }
    }
    c=c>='z'?'a':(char)(c+1);
    System.out.println("Alpaha out "+c);
    o.setFlag(true);
    o.notifyAll();
    }
    }
    }
    }class NumberOut implements Runnable
    {
    private Out o;
    int x=0;
    public NumberOut(Out o)
    {
    this.o = o;
    }
    public void run()
    {
    while(true)
    {
    try
    {
    Thread.sleep(1000);
    }
    catch(InterruptedException e)
    {
    e.printStackTrace();
    }
    synchronized(o) 
    {
    while(!o.getFlag())
    {
    try
    {
    o.wait();
    }
    catch(InterruptedException ie)
    {
    ie.printStackTrace();
    }
    }
    x=x>=100?1:x+1;
    System.out.println("Number out "+x);
    o.setFlag(false);
    o.notifyAll();
    }
    }
    }
    }
    class Out
    {
    private boolean flag=false;
    public void setFlag(boolean flag)
    {
    this.flag=flag;
    }
    public boolean getFlag()
    {
    return flag;
    }
    }