如何同时启动两个线程,一个不停输出111,一个不停输出222,用线程可以做到吗,怎么做?

解决方案 »

  1.   

    public static void main(String[] args) {
            Thread thread1 = new Thread(new Runnable(){
                public void run() {
                    while(true){
                        System.out.println("111");
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException ex) {
                        }
                    }
                }
            });
            
            Thread thread2 = new Thread(new Runnable(){
                public void run() {
                    while(true){
                        System.out.println("222");
                        try {
                            Thread.sleep(200);
                        } catch (InterruptedException ex) {
                        }
                    }
                }
            });        thread1.start();
            thread2.start();
        }
      

  2.   

    只能这样了,多线程就是动态分配cpu时间,不可能让cpu在同一时间执行两个任务,除非用双核心的cpu,而且要操作系统支持哦。
      

  3.   

    说是多线程,但在单CPU下,同一时刻只能运行一个线程。
      

  4.   

    public class Thready {
        public static void main( String args [] ) {
            new MyThread("111").start(  );
            new MyThread("222").start(  );
        }
    } // end of class Threadyclass MyThread extends Thread {
        String message;    MyThread ( String message ) {
            this.message = message;
        }    public void run(  ) {
            while ( true )
                System.out.println( message );
        }
    }
      

  5.   

    谢谢楼上两位提供的代码,但是它们都产生了两个.class,能不能只有一个.class的实现啊?
      

  6.   

    启动线程的start()方法要用到run()方法,而Thread类的run()为空,所以必须新建 Thread的子类,自己写run()方法内容,覆盖Thread类的run()方法.
      

  7.   

    你这不是强人所难嘛。两个类有什么关系?就我所知,一个类做不到构造两个线程,匿名内隐类也是类也会生成一个class文件的
      

  8.   

    public class JavaProject
    {
    public static void main(String[] args) {
          Thread T1 = new myThread("111");
          Thread T2 = new myThread("222");
          T1.start();
          T2.start();
    }
    }class myThread extends Thread
    {
      public myThread(String str)
      {
      super(str);
      }
     
      public void run()
      {
      while(true)
      {
      try{
        sleep((int)Math.random()*1000);
      }catch(InterruptedException e)
    {
      System.out.println(e);
      System.exit(1);
    }
     
      System.out.println(getName());
      }
      }
    }