public class MyThread extends Thread { public MyThread(String name) { super(name); } public void run() { for(int i=0;i<5;i++){ try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(super.getName()+":启动线程..."); } } }
public class MyThread2 extends Thread { public MyThread2(String name) { super(name); } public void run() { for(int i=0;i<5;i++){ try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(super.getName()+":启动线程..."); } } }
public class TestThread { public static void main(String[] args) throws InterruptedException { MyThread2 myThread2 = new MyThread2("线程2"); myThread2.start(); Thread.sleep(2000); test1(); test(); System.out.println("当前线程:"+Thread.currentThread().getName());//当前线程名字 MyThread myThread = new MyThread("线程1"); myThread.start(); // 匿名内部线程实现runnable Runnable r = new Runnable() { public void run() { System.out.println("匿名Runable....."); } }; new Thread(r).start(); // 匿名内部类 new Thread() { public void run() { System.out.println("匿名Thread......"); } }.start(); } public static void test() { System.out.println("test...."); } public static void test1() { System.out.println("test1...."); } } 结果: 线程2:启动线程... 线程2:启动线程... 线程2:启动线程... test1.... test.... 当前线程:main 线程2:启动线程... 匿名Runable..... 匿名Thread...... 线程2:启动线程... 线程1:启动线程... 线程1:启动线程... 线程1:启动线程... 线程1:启动线程... 线程1:启动线程...
原文:https://www.cnblogs.com/whx20100101/p/9862331.html