package com.fgy.demo01; public class MyThread extends Thread { @Override public void run() { for (int i = 0; i < 20; i++) { System.out.println("run:" + i); } } }
/** * 创建多线程程序的第一种方式,创建Thread类的子类 * 多次启动一个线程是非法的,特别是当线程已经结束执行后,不能再重新启动 * java程序属于抢占式调度,哪个线程的优先级高,哪个线程就优先执行,同一个优先级,随机选择一个执行 */ public class Demo01Thread{ public static void main(String[] args) { MyThread mt = new MyThread(); mt.start(); for (int i = 0; i < 20; i++) { System.out.println("main:" + i); } } }
package com.fgy.demo01; public class MyRunnable implements Runnable { @Override public void run() { for (int i = 0; i < 20; i++) { System.out.println(Thread.currentThread().getName() + ":" + i); } } }
package com.fgy.demo01; /** * 创建多线程程序的第二种方式,实现Runnable接口 */ public class Demo02Thread { public static void main(String[] args) { new Thread(new MyRunnable()).start(); for (int i = 0; i < 20; i++) { System.out.println(Thread.currentThread().getName() + ":" + i); } } }
package com.fgy.demo01; /** * 匿名内部类方式实现线程的创建 */ public class InnerClassThread { public static void main(String[] args) { new Thread() { @Override public void run() { for (int i = 0; i < 20; i++) { System.out.println(getName() + ":" + i); } } }.start(); new Thread( new Runnable() { @Override public void run() { for (int i = 0; i < 20; i++) { System.out.println(Thread.currentThread().getName() + ":" + i); } } } ).start(); } }
原文:https://www.cnblogs.com/roadlandscape/p/12104437.html