java 多线程(Thread,Runnable)

来源:互联网 发布:cloudtv for mac 编辑:程序博客网 时间:2024/06/10 16:56
1.继承Thread 方式实现多线程
package test;/** * 测试多线程继承方式 *  * @author LiuPeng 2013-9-11 下午04:49:25 */public class ThreadExt {/** * @param args */public static void main(String[] args) {Thread th = new TestThread("张三");th.start();Thread th1 = new TestThread("李四");th1.start();}}//继承Threadclass TestThread extends Thread {public TestThread(String name) {super(name);}// 线程启动运行此方法public void run() {for (int i = 0; i < 5; i++) {System.out.println(this.getName() + " :" + i);}}}


2.实现Runnable 方式实现多线程

package test;/** * 通过实现Runnable 接口实现多线程 * @author LiuPeng * 2013-9-11 下午04:53:22 */public class ThreadImp {public static void main(String[] args) {MyThread my = new MyThread();//实现资源共享new Thread(my).start();// 这种方式在Thread中是不可以的new Thread(my).start();//        new Thread(my).start();}}class MyThread implements Runnable {public void run() {for (int i = 0; i < 20; i++) {System.out.println(i);}}}

选择实现Runnable 方式可以多继承,资源共享!


原创粉丝点击