一、继承Thread类
public class TestThread1 extends Thread { @Override public void run() { for(int i=1; i<=100; i++) { System.out.println("线程1的" + i); try { sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }
public class TestThread2 extends Thread { @Override public void run() { for(int i=1; i<=100; i++) { System.out.println("线程2的:" + i); try { sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } } }
public class Test { public static void main(String[] args) { TestThread1 thread1 = new TestThread1(); TestThread2 thread2 = new TestThread2(); thread1.start(); thread2.start(); } }
因为打一次要睡100ms,所以是一个线程一次
二、实现Runnable接口
public class TestRunnable1 implements Runnable { @Override public void run() { for(int i=0; i<100; i++) { System.out.println("线程1: " + i); } } }
public class TestRunnable2 implements Runnable { @Override public void run() { for(int i=0 ;i<100; i++) { System.out.println("线程2: " + i); } } }
public class Test { public static void main(String[] args) { TestRunnable1 run1 = new TestRunnable1(); TestRunnable2 run2 = new TestRunnable2(); new Thread(run1).start(); new Thread(run2).start(); } }
三、继承Callable接口
public class TestCallable1 implements Callable<Integer> { @Override public Integer call() throws Exception { for(int i=0; i<100; i++) { System.out.println("线程1: " + i); } return null; } }
public class TestCallable2 implements Callable<Integer> { @Override public Integer call() throws Exception { for(int i=0; i<100; i++) { System.out.println("线程2: " + i); } return 0; } }
public class Test { public static void main(String[] args) throws InterruptedException, ExecutionException { FutureTask<Integer> task1 = new FutureTask<>(new TestCallable1()); FutureTask<Integer> task2 = new FutureTask<>(new TestCallable2()); new Thread(task1).start(); new Thread(task2).start(); System.out.println("[线程返回数据]: " + task1.get()); System.out.println("[线程返回数据]: " + task2.get()); } }
四、线程池
public class TestThreadPool { public static void main(String[] args) { ExecutorService e = Executors.newCachedThreadPool(); e.execute(new Test1()); e.execute(new Test2()); } } class Test1 implements Runnable{ @Override public void run() { for(int i=0; i<100; i++) { System.out.println("线程1:" + i); } } } class Test2 implements Runnable{ @Override public void run() { for(int i=0; i<100; i++) { System.out.println("线程2:" + i); } } }