public class MyThread extends Thread { @Override public void run() { for (int i = 1; i <= 5; i++) { //返回当前线程的名字 System.out.println(Thread.currentThread().getName() + " " + i); } }
public static void main(String[] args) { for (int i = 1; i <= 6; i++) { //获取当前线程的名字 System.out.println(Thread.currentThread().getName() + " " + i); if (i == 3) { //创建第一个线程 MyThread thread1 = new MyThread(); //启动第一个线程 thread1.start();
public class MyThread implements Runnable { @Override public void run() { for (int i = 1; i <= 5; i++) { //返回当前线程的名字 System.out.println(Thread.currentThread().getName() + " " + i); } }
public static void main(String[] args) { for (int i = 1; i <= 6; i++) { //获取当前线程的名字 System.out.println(Thread.currentThread().getName() + " " + i); if (i == 3) { //创建Runnable的实例:MyThread MyThread myThread = new MyThread();
//创建第一个线程,并将Runnable的实例:MyThread,作为Thread的target来创建Thread对象 Thread thread1 = new Thread(myThread, "第一个线程"); //启动第一个线程 thread1.start();