1、用多线程实现,三个学生同时从教室跑到一个饮水机旁,然后排队接水,先接完水的要在饮水机旁等待,直到所有的学生都接完水后,一块在返回到教室。2、三个线程都要完成打印1-100但在打印时要求三个线程分阶段打印,每个阶段为10个数字,即都先打印完1-10,之后都再开始打印第二阶段11-20,然后都再开始打印第三阶段、、、、、依次类推。3、用多线程描述实现10张票(票的编号为1-10)三个窗口来同时买,要把每个窗口买的票的编号打出来。 

解决方案 »

  1.   

    2、三个线程都要完成打印1-100但在打印时要求三个线程分阶段打印,每个阶段为10个数字,即都先打印完1-10,之后都再开始打印第二阶段11-20,然后都再开始打印第三阶段、、、、、依次类推。class mt extends Thread {
        private static int count;
        @Override
        public void run() {
            for (int i = 0; i < 100;) {
                System.out.println(getName() + ":" + (++i));
                if (i % 10 == 0) {
                    synchronized (this) {
                        count++;
                    }
                    while (i / 10 > count / 3) {//在这里等待其它线程
                        try {
                            Thread.sleep(0);
                        } catch (InterruptedException ex) {
                        }
                    }
                }
            }
            try {
                Thread.sleep(1);//为了让多线程明显 1ms
            } catch (InterruptedException ex) {
            }
        }
    }public class Main {    public static void main(String[] args) {
            Thread t1 = new mt();
            Thread t2 = new mt();
            Thread t3 = new mt();
            t1.start();
            t2.start();
            t3.start();
        }
    }
      

  2.   

    3、用多线程描述实现10张票(票的编号为1-10)三个窗口来同时买,要把每个窗口买的票的编号打出来。 class ti{//票
        static int t=1;
        static synchronized int getT(){
            return t>10?-1:t++;
        }
    }
    class mt extends Thread {//窗口
        String name;
        mt(String n){
            name = n;
        }
        @Override
        public void run() {
            int i;
            while((i=ti.getT())!=-1){
                System.out.println(name+"卖出票:"+i);
                System.out.flush();
                try {
                    Thread.sleep(0);
                } catch (InterruptedException ex) {
                }
            }
        }
    }public class Main {    public static void main(String[] args) {
            Thread t1 = new mt("1号窗口");
            Thread t2 = new mt("2号窗口");
            Thread t3 = new mt("3号窗口");
            t1.start();
            t2.start();
            t3.start();
        }
    }
      

  3.   

    第一题:
    http://blog.csdn.net/YidingHe/archive/2009/11/23/4854915.aspx