日期:2014-05-20  浏览次数:20631 次

Java 多线程 的并发执行
先看看下面这段简单的代码:

class   Thread1   extends   Thread   {        
        private   int   x   =   0;

        //非常耗时的工作,   比如计算,   监视...
        public   void   run()   {                
                while   (true)   {
                        x   =   (x   <   100)   ?   (x   +   1)   :   0;
                }
        }
}

class   Thread2   extends   Thread   {
        public   void   run()   {
                for   (int   i   =   0;   i   <   10;   i++)   {
                        System.out.println(i   +   "Thread   2   is   running   ... ");
                }
        }
}

public   class   Main   {
        public   static   void   main(String[]   args)   {
                Thread1   t1   =   new   Thread1();
                t1.run();

                //t1   没有执行完毕,   就不会执行下面的代码
                System.out.println( "Start   another   thread ");
                Thread2   t2   =   new   Thread2();
                t2.run();
        }
}

这算不算多线程程序?

t1.run()   做一项非常长时间的工作,  

发现   线程   t1   启动后,   如果   t1.run()   没有执行完毕,   就不会执行其他的代码
有什么方法可以一边执行   t1.run(),   一边执行其他的代码   ?

------解决方案--------------------
t1.run();
t2.run();

换成

t1.start();
t2.start();

start方法才启动线程
run只是一个普通的方法 而不是启动线程的方法

------解决方案--------------------
start方法才启动线程
run只是一个普通的方法 而不是启动线程的方法

同意楼上~
------解决方案--------------------
-_-#~!

t1:
while (true) {
x = (x < 100) ? (x + 1) : 0;
}
-------------
死循环,根本轮不到t2;加上sleep,或waite , notify
------解决方案--------------------
run()是线程启动后才执行的
------解决方案--------------------
不算,只是普通的方法调用,因为你的线程都没有启动阿~
把main()里的t1.run() t2.run() 换成t1.start() t2.start()
------解决方案--------------------
上面的都已经说得很清楚了, 线程我也只懂基础, 不过计划接下来看Java Concurrency in practice...
------解决方案--------------------

前面的说的都没错,用start方法启动后,会产生一个新的Runnable状态的线程,新线程会自动做run里的任务. 如果直接调用run方法,则不会产生新的线程,只是在当前线程里做run任务.