【并发编程】实现多线程的两种方法
2014-10-10 17:52
603 查看
Java语言已经内置了多线程支持,所有实现Runnable接口的类都可被启动一个新线程。
新线程会执行该实例的run()方法,当run()方法执行完毕后,线程就结束了。一旦一个线程执行完毕,这个实例就不能再重新启动,只能重新生成一个新实例,再启动一个新线程。
Thread类是实现了Runnable接口的一个实例,它代表一个线程的实例,并且,启动线程的唯一方法就是通过Thread类的start()实例方法。
注意:直接调用run()方法并不会启动一个新线程,它和调用一个普通的Java方法没有什么区别。有两个方法可以实现自己的线程。
ONE
扩展(继承)Thread类,并复写run()方法,就可以启动新线程并执行自己定义的run()方法。
在合适的地方启动线程即可。
TWO
如果类已经extends另一个类,就无法直接继承Thread类,那么,必须实现一个Runnable接口。
为了启动MyThread,需要首先实例化一个Thread,并传入自己的MyThread实例。
Thread类的部分源代码如下:
新线程会执行该实例的run()方法,当run()方法执行完毕后,线程就结束了。一旦一个线程执行完毕,这个实例就不能再重新启动,只能重新生成一个新实例,再启动一个新线程。
Thread类是实现了Runnable接口的一个实例,它代表一个线程的实例,并且,启动线程的唯一方法就是通过Thread类的start()实例方法。
Thread t = new Thread(); t.start();start()启动一个新线程,并执行run()方法。Thread类默认的run()方法什么也不做就退出了。
注意:直接调用run()方法并不会启动一个新线程,它和调用一个普通的Java方法没有什么区别。有两个方法可以实现自己的线程。
ONE
扩展(继承)Thread类,并复写run()方法,就可以启动新线程并执行自己定义的run()方法。
public class MyThread extends Thread { public run() { System.out.println("MyThread.run()"); } }
在合适的地方启动线程即可。
new MyThread().start();
TWO
如果类已经extends另一个类,就无法直接继承Thread类,那么,必须实现一个Runnable接口。
public class MyThread extends OtherClass implements Runnable { public run() { System.out.println("MyThread.run()"); } }
为了启动MyThread,需要首先实例化一个Thread,并传入自己的MyThread实例。
MyThread myt = new MyThread(); Thread t = new Thread(myt); t.start();事实上,当传入一个Runnable target参数给Thread后,Thread的run()方法就会调用target.run()。
Thread类的部分源代码如下:
/** * Starts the new Thread of execution. The <code>run()</code> method of * the receiver will be called by the receiver Thread itself (and not the * Thread calling <code>start()</code>). * * @throws IllegalThreadStateException if the Thread has been started before * * @see Thread#run */ public synchronized void start() { if (hasBeenStarted) { throw new IllegalThreadStateException("Thread already started."); // TODO Externalize? } hasBeenStarted = true; VMThread.create(this, stackSize); }
/** * Calls the <code>run()</code> method of the Runnable object the receiver * holds. If no Runnable is set, does nothing. * * @see Thread#start */ public void run() { if (target != null) { target.run(); } }
相关文章推荐
- java并发编程之:多线程实现单例的两种方法
- 【Java并发编程】实现多线程的两种方法
- 【Java并发编程】之十五:并发编程中实现内存可见的两种方法比较:加锁和volatile变量
- 【Java并发编程】之十五:并发编程中实现内存可见的两种方法比较:加锁和volatile变量
- 转:【Java并发编程】之十五:并发编程中实现内存可见的两种方法比较:加锁和volatile变量
- 【Java并发编程】之十五:并发编程中实现内存可见的两种方法比较:加锁和volatile变量(r)
- 【Java并发编程】之十五:并发编程中实现内存可见的两种方法比较:加锁和volatile变量
- 并发编程实战 1.1. 实现多线程的两种方式
- 【Java并发编程】之十五:并发编程中实现内存可见的两种方法比较:加锁和volatile变量
- 【Java并发编程】之十五:并发编程中实现内存可见的两种方法比较:加锁和volatile变量
- 第十五篇:并发编程中实现内存可见的两种方法比较:加锁和volatile变量
- Java并发编程之一:多线程的两种实现
- java并发编程(九)--并发编程中实现内存可见的两种方法比较:加锁和volatile变量
- 【Java并发编程】:并发编程中实现内存可见的两种方法比较:加锁和volatile变量
- 网络编程(6)单进程多线程并发服务器实现
- 【Java并发编程】之六:Runnable和Thread实现多线程的区别(含代码)
- 【java实现多线程的两种方法】
- 【Java并发编程】之六:Runnable和Thread实现多线程的区别(含代码)
- 多线程编程--5种方法实现线程同步
- 两种实现多线程的方法有什么区别