一、自定义线程(继承Thread)java
package com.ljb.app.thread; /** * 自定义线程(使用继承Thread方法) * @author LJB * @version 2015年3月6日 */ public class MyThread extends Thread{ private int count = 0; public void run() { while (count < 100) { count++; } System.out.println("count is " + count); } }
二、启动线程app
package com.ljb.app.thread; /** * 启动自定义线程 * @author LJB * @version 2015年3月6日 */ public class TestMyThread { /** * @param args */ public static void main(String[] args) { // 建立线程实例 MyThread myThread = new MyThread(); /* * start()方法做用: * 该方法会使操做系统初始化一个新的线程 * 由这个线程执行线程对象的run()方法 */ myThread.start(); } }
缺点:不能再继承其余类测试
三、建立线程(实现Runnable接口)spa
package com.ljb.app.thread; /** * 建立类(实现Runnable接口) * @author LJB * @version 2015年3月6日 */ public class MyRunnable implements Runnable{ private int count = 0; public void run() { System.out.println("实现Runnable接口的线程已启动"); while (count < 100) { count++; } System.out.println("count is " + count); } }
四、启动线程操作系统
package com.ljb.app.thread; /** * 建立测试类 * @author LJB * @version 2015年3月6日 */ public class TestRunnable { /** * @param args */ public static void main(String[] args) { // 建立实现Runnable接口的类对象 MyRunnable myRunnable = new MyRunnable(); // 建立线程,调用Thread带参构造方法 Thread thread = new Thread(myRunnable); // 启动线程 thread.start(); } }