创建一个类MyThread类继承Thread类,重写run()方法, run()方法体内写要执行的代码。
/** * 继承Thread类创建线程 * 重写run()方法 * @author dudu * */ public class MyThread extends Thread{ @Override public void run() { System.out.println("我是重写的run方法----继承Mythread类"); } }新建一个测试类,main方法里,实例化MyThread ,并用对象调用start()方法启动线程。
/** * 测试 继承Thread类创建线程 * @author dudu * */ public class TestMyThread { public static void main(String[] args) { MyThread m = new MyThread();//实例化MyThread m.start();//调用start()方法启动线程 } }执行结果
我是重写的run方法----继承Mythread类多线程的话就多实例化一个对象
public class MyThread extends Thread{ @Override public void run() { //System.out.println("我是重写的run方法----继承Mythread类"); for(int i=1;i<=5;i++) { //当前线程的线程名 System.out.println(Thread.currentThread().getName()+" 第"+i+"次执行"); } } }测试
/** * 测试 继承Thread类创建线程 * @author dudu * */ public class TestMyThread { public static void main(String[] args) { MyThread m1 = new MyThread();//实例化MyThread m1.start();//调用start()方法启动线程 MyThread m2 = new MyThread(); m2.start(); } }执行结果
线程2 第1次执行 线程1 第1次执行 线程1 第2次执行 线程1 第3次执行 线程2 第2次执行 线程2 第3次执行 线程1 第4次执行 线程2 第4次执行 线程2 第5次执行 线程1 第5次执行创建一个MyRunnable类,实现Runnable接口,并且也要有run()方法
/** * 实现Runnable接口创建线程 * 重写run()方法 * @author dudu * */ public class MyRunnable implements Runnable{ @Override public void run() { System.out.println("我是run方法----实现Runnable接口"); } }新建一个测试类,main方法里,实例化,并用对象调用start()方法启动线程。
/** * 测试 实现Runnable接口创建线程 * @author dudu * */ public class TestMyRunnable { public static void main(String[] args) { //Runnable接口new一个MyRunnable 实例化 Runnable r = new MyRunnable(); //实例化Thread 并把Runnable 对象放入参数, Thread t = new Thread(r); t.start();//调用start方法启动线程 } }执行结果–线程交替执行
我是run方法----实现Runnable接口多线程和上述同理
public class MyRunnable implements Runnable{ @Override public void run() { for(int i=1;i<=5;i++) { System.out.println(Thread.currentThread().getName()+"第"+i+"次执行"); } } } public class TestMyRunnable { public static void main(String[] args) { //Runnable接口new一个MyRunnable 实例化 Runnable r = new MyRunnable(); //实例化Thread 并把Runnable 对象放入参数, Thread t1 = new Thread(r,"线程1");//后面可以给线程起名,可以不写 Thread t2 = new Thread(r,"线程2"); t1.start();//调用start方法启动线程 t2.start(); } }执行结果-线程交替执行
线程2第1次执行 线程1第1次执行 线程2第2次执行 线程2第3次执行 线程1第2次执行 线程2第4次执行 线程1第3次执行 线程2第5次执行 线程1第4次执行 线程1第5次执行以上就是线程简单创建的两种方式,不过推荐用实现Runnable接口的方法创建线程。