Java 线程基础 之 创建线程
继承Thread类创建线程
-
自定义Thread
public class MyThread extends Thread { @Override public void run() { //通过Thread类把run方法包装成线程体 System.out.println(getName() + " *"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(getName() + " #"); } }
-
测试代码
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName());
new MyThread().start();
new MyThread().start();
new MyThread().start();
}
结果:
步骤:
- 创建一个实现了Runnable接口的类,重写它的run()方法
- 创建Thread对象,将第一个创建的Runnable类的对象作为参数传递过来
- 通过Thread对象来启动线程
-
自定义Runnable
public class MyRunnable implements Runnable { @Override public void run() { System.out.println(Thread.currentThread().getName() + " *"); try { Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + " #"); } }
-
测试代码
public static void main(String[] args) { System.out.println(Thread.currentThread().getName()); MyRunnable runnable = new MyRunnable(); new Thread(runnable, "Thread-0 ").start(); new Thread(runnable, "Thread-1 ").start(); new Thread(runnable, "Thread-2 ").start(); }
结果: 采用Labmda表达式改写上面代码
public static void main(String[] args) {
System.out.println(Thread.currentThread().getName());
Runnable runnable = () -> {
System.out.println(Thread.currentThread().getName() + " *");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " #");
};
new Thread(runnable, "Thread-0 ").start();
new Thread(runnable, "Thread-1 ").start();
new Thread(runnable, "Thread-2 ").start();
}
使用Callable创建线程
- 自定义Callable
public class MyCallable implements Callable { private String arg ; public MyCallable(String arg ) { this.arg = arg; } @Override public String call() { //线程执行体 return arg.toUpperCase(); } }
- 测试代码:
public static void main(String[] args) throws Exception { // 使用Thread FutureTask task1 = new FutureTask(new MyCallable("helloworld")); new Thread(task1,"有返回值的线程").start(); String res = task1.get();//FutureTask对象封装了Callable对象的call方法的返回值 System.out.println(res); // 使用ExecutorService FutureTask task2 = new FutureTask(new MyCallable("Goodmoning")); ExecutorService pool = Executors.newCachedThreadPool(); pool.submit(task2); System.out.println(task2.get()); pool.shutdown(); // FutureTask task3= new FutureTask(new MyCallable("NicetoMeetYou")); ExecutorService pool2 = Executors.newCachedThreadPool(); pool2.execute(task3); System.out.println(task3.get()); pool2.shutdown(); }
结果: