创建线程的几种方式,以及为什么启动线程不用run,而用start方法!!!

来源:互联网 发布:zknu教务网络管理系统 编辑:程序博客网 时间:2024/05/22 16:05


首先,我们大家都知道,创建线程的两种蛀主要的方法,一种是继承Thread类,另一种是实现Runnable接口。对于第一种创建线程的方式有两个不足:
1.当前线程重写run方法定义该线程要完成的工作,这就导致了任务是定义在线程内部的,于是线程与任务有一个强耦合关系,不利于线程的重用。
2.由于java是单继承的,这就导致了若继承了线程就无法继承其他类,在实际开发中经常会出现继承冲突的问题(单继承极限)。


</pre><pre name="code" class="java">
package sync;/** * 线程的创建方式有两种: * 方式一:继承Thread类并重写run方法 * @author Administrator * */public class ThreadDemo1 {public static void main(String[] args) {/* * 有先后顺序的执行称为同步的执行 *///for(int i =0;i<500;i++){//System.out.println("你是谁啊?");//System.out.println("我是查水表的");//}/* * 代码各干各的,则是异步执行. */Thread t1 = new MyThread1();//t1.run();Thread t2 = new MyThread2();/* * 启动线程不要直接调用run方法,而是 * 应该调用start方法,这样线程才会并发运行, * run方法会在线程启动后自动被调用. */t1.start();t2.start();}}class MyThread1 extends Thread{public void run() {for(int i =0;i<5000;i++){System.out.println("你是谁呀?");}}}class MyThread2 extends Thread{public void run() {for(int i =0;i<5000;i++){System.out.println("我是查水表的。");}}}

Thread.java 类中的start() 方法通知“线程规划器”此线程已经准备 就绪,等待调用线程对象的run() 方法。这个过程其实就是让系统安排 一个时间来调用Thread 中的run() 方法,也就是使线程得到运行,启动 线程,具有异步执行的效果。如果调用代码thread.run() 就不是异步执行 了,而是同步,那么此线程对象并不交给“线程规划器”来进行处理, 而是由main 主线程来调用run() 方法,也就是必须等run() 方法中的代 码执行完后才可以执行后面的代码。 

package sync;/** * 第二种创建线程的方式: * 实现Runnable接口来单独定义线程任务. * @author Administrator * */public class ThreadDemo2 {public static void main(String[] args) {Runnable runnable1 = new MyRunnable1();Runnable runnable2 = new MyRnunable2();Thread thread1 = new Thread(runnable1);Thread thread2 = new Thread(runnable2);thread1.start();thread2.start();}}class MyRunnable1 implements Runnable{public void run(){for(int i =0;i<500;i++){System.out.println("你是谁呀?");}}}class MyRnunable2 implements Runnable{public void run(){for(int i =0;i<500;i++){System.out.println("我是查水表的.");}}}

package sync;/** * 以匿名内部类完成方式一与方式二的创建. * @author Administrator * */public class ThreadDemo3 {public static void main(String[] args) {Thread t1 = new Thread(){public void run(){for(int i=0;i<500;i++){System.out.println("你是谁?");}}};t1.start();Runnable run = new Runnable(){public void run(){for(int i=0;i<500;i++){System.out.println("我是查水表的.");}}};Thread t2 = new Thread(run);t2.start();}}



参考资料:Java多线程编程核心技术。


0 0