继承Thread类
package com.learn; public class Main { public static void main(String[] args) { MyThread t1 = new MyThread("t1"); MyThread t2 = new MyThread("t2"); t1.start(); t2.start(); } } class MyThread extends Thread { private String name; public MyThread(String name) { this.name = name; } @Override public void run() { while(true) { // super.run(); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(name); } } }
使用Runnable接口
package com.learn; public class Main { public static void main(String[] args) { Runnable runnablet3=new MyRunnable("t3"); Thread t3=new Thread(runnablet3); t3.start(); Runnable runnablet4=new MyRunnable("t4"); Thread t4=new Thread(runnablet4); t4.start(); } } class MyRunnable implements Runnable { private String name; public MyRunnable(String name) { this.name = name; } @Override public void run() { // TODO Auto-generated method stub while(true) { // super.run(); try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(name); } } }
Java多线程编程核心技术01-两种方式的多线程实现方法,那也就意味着构造函数Thread(Runnable target)不光可以传入Runnable接口的对象,还可以传入一个Thread类的对象,这样做完全可以将一个Thread对象中的run()方法交由其他的线程进行调用。