Java多线程基础
1.通过继承Thread类实现多线程:
public class Thread1 extends Thread{ /** * 该线程类的线程体 */ public void run(){ //线程体 for (int i = 0; i < 100; i++) { System.out.println(this.getName()+":"+i); } } public static void main(String[] args) { Thread1 a = new Thread1(); a.start(); Thread1 b = new Thread1(); b.start(); } }
2.通过实现Runnable接口实现多线程:
public class Thread2 implements Runnable{ int threadId; public Thread2(int id) { super(); this.threadId = id; } @Override public void run() { for (int i = 0; i < 100; i++) { System.out.println(this.threadId+":"+i); } } public static void main(String[] args) { Thread a = new Thread(new Thread2(1)); a.start(); Thread b = new Thread(new Thread2(2)); b.start(); } }