1.继承thread(重写run)
public class ThreadDemo { public static void main(String[] args) { TestThread t1 = new TestThread("thread1"); TestThread t2 = new TestThread("thread2"); t1.start(); t2.start(); } } class TestThread extends Thread { String name; public TestThread(String name) { this.name = name; } @Override public void run() { for (int i = 0; i < 100; i++) { System.out.println(this.name + ":" + i); } } }
Thread的run和start有什么区别
run()方法:
是在主线程中执行方法,和调用普通方法一样;(按顺序执行,同步执行)
start()方法:
是创建了新的线程,在新的线程中执行;(异步执行)
2.实现runnable(重写run)
package test; public class RunnableDemo { public static void main(String[] args) { TestRunnable r1 = new TestRunnable("runnable-1"); TestRunnable r2 = new TestRunnable("runnable-2"); r1.start(); r2.start(); } } class TestRunnable implements Runnable { String name; Thread thread; public TestRunnable(String name) { this.name = name; } @Override public void run() { for (int i = 0; i < 100; i++) { System.out.println(this.name + ":" + i); } } public void start() { System.out.println("Starting " + this.name); if (thread == null) { thread = new Thread(this, this.name); thread.start(); } } }
3.匿名内部类(重写run)
package test; public class test3 { public static void main(String[] args) { System.out.println("-----多线程创建开始-----"); Thread thread = new Thread(new Runnable() { public void run() { for (int i = 0; i< 100; i++) { System.out.println("i:" + i); } } }); Thread thread2 = new Thread(new Runnable() { public void run() { for (int i = 0; i< 100; i++) { System.out.println("j:" + i); } } }); thread.start(); thread2.start(); System.out.println("-----多线程创建结束-----"); } }
4.Callable(重写run)
package test; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; /** * callable */ public class CallableDemo { static class MyThread implements Callable<String> { @Override public String call() throws Exception { return "Hello world"; } } static class MyRunnable implements Runnable { @Override public void run() { } } public static void main(String[] args) { ExecutorService threadPool = Executors.newSingleThreadExecutor(); Future<String> future = threadPool.submit(new MyThread()); try { System.out.println(future.get()); } catch (Exception e) { } finally { threadPool.shutdown(); } } }