自定义的线程类:
public class MyRunnableThread implements Runnable { @Override public void run() { for (int i = 0; i < 100; i++) { try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } //创建线程后.再调用线程的getName方法 System.out.println(Thread.currentThread().getName()+"-"+i); } } }
main方法:
public class Main { public static void main(String[] args) { //依然要创建Thread对象才能使用多线程 // 这里用的是Thread(Runnable target)构造方法 // 或Thread(Runnable target,String name)构造方法 //将Runnable接口的实现类对象包装为一个线程对象 Thread t1 = new Thread(new MyRunnableThread(),"线程1"); Thread t2 = new Thread(new MyRunnableThread(),"线程2"); t1.start(); t2.start(); } }