|
发表于 2013-11-28 16:39:48
|
显示全部楼层
线程a可能被阻塞(也就是你说的打断),然后执行线程b,给你个简单的例子
- public class Ex_3 implements Runnable {
- String threadName;
- public Ex_3(String threadName)
- {
- System.out.println(threadName);
- this.threadName = threadName;
- }
-
- public void run()
- {
- for(int i = 0 ; i < 3 ; ++i)
- {
- System.out.println("正在运行的线程:"+threadName);
-
- try
- {
- Thread.sleep((int)Math.random()*1000);
- }
- catch(Exception ex)
- {
- System.out.println(ex);
- }
- }
- }
- public static void main(String[] args)
- {
- System.out.println("开始运行主函数");
- Ex_3 t1 = new Ex_3("first");
- Ex_3 t2 = new Ex_3("second");
-
- Thread tt1 = new Thread(t1);//线程1
- Thread tt2 = new Thread(t2);//线程2
-
- tt1.start();//线程1启动
- tt2.start();//线程2启动
-
- System.out.println("主函数结束");
- }
- }
复制代码 这段程序的两次运行结果:
(1)。- 开始运行主函数
- first
- second
- 主函数结束
- 正在运行的线程:first
- 正在运行的线程:first
- 正在运行的线程:first
- 正在运行的线程:second
- 正在运行的线程:second
- 正在运行的线程:second
复制代码 (2)。- 开始运行主函数
- first
- second
- 主函数结束
- 正在运行的线程:second
- 正在运行的线程:first
- 正在运行的线程:second
- 正在运行的线程:first
- 正在运行的线程:second
- 正在运行的线程:first
复制代码 |
|