1. Inherit the Thread class
public class ThreadCreator extends Thread{ public static void main(String[] args) { //第一种方式: ThreadCreator creator = new ThreadCreator(); Thread thread = new Thread(creator,"线程1"); thread.start(); //第二种方式: Thread thread = new ThreadCreator(); thread.start(); //第三种方式: new ThreadCreator().start(); } @Override public void run() { System.out.println(Thread.currentThread().getName() + "run"); } }
2. Implement the Runnable interface
(free learning video tutorial sharing: java video tutorial)
public class ThreadCreator implements Runnable{ public static void main(String[] args) { ThreadCreator creator = new ThreadCreator(); Thread thread = new Thread(creator,"线程1"); thread.start(); } @Override public void run() { System.out.println(Thread.currentThread().getName() + "run"); } }
3. Implement the Callable interface
public class ThreadCreator implements Callable<Integer> { public static void main(String[] args) throws ExecutionException, InterruptedException { ThreadCreator creator = new ThreadCreator(); FutureTask futureTask = new FutureTask(creator); Thread thread = new Thread(futureTask,"线程"); thread.start(); System.out.println(futureTask.get()); } @Override public Integer call() { return 1024; } }
4. Thread pool ExecutorService
public class ThreadCreator{ static ExecutorService service = Executors.newFixedThreadPool(5); public static void main(String[] args) throws ExecutionException, InterruptedException { //execute无返回值 service.execute(new ThreadTask(1,"1")); //submit有返回值 Future<Integer> result = service.submit(new ThreadTaskCall()); System.out.println(result.get()); service.shutdownNow(); } static class ThreadTask implements Runnable{ private int param1; private String param2; public ThreadTask(int param3,String param4){ this.param1 = param3; this.param2 = param4; } @Override public void run() { System.out.println(param1+param2); } } static class ThreadTaskCall implements Callable<Integer>{ @Override public Integer call() throws Exception { return 1024; } } }
The difference between submit and execute in the thread pool:
(1 ) The acceptable task types are different: execute can only accept Runnable tasks, and submit can also accept Callable tasks.
(2) Return value: execute has no return value. Once the task is submitted, the execution result cannot be monitored in the current thread. Submit has a Future type return value, which is used to receive return values or respond to exceptions. Obtained through the get() method.
The bottom layer of submit is still called execute, but it is encapsulated with a future layer on this basis, and all exceptions generated during the execution are encapsulated in a variable:
public void run() { if (state != NEW || !UNSAFE.compareAndSwapObject(this, runnerOffset, null, Thread.currentThread())) return; try { Callable<V> c = callable; if (c != null && state == NEW) { V result; boolean ran; try { result = c.call(); ran = true; } catch (Throwable ex) { result = null; ran = false; setException(ex); } if (ran) set(result); } } finally { runner = null; int s = state; if (s >= INTERRUPTING) handlePossibleCancellationInterrupt(s); } } protected void setException(Throwable t) { if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) { outcome = t; UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state finishCompletion(); } }
In addition, spring The schedule annotation uses the submit processing method for reference.
5. Anonymous inner class
public class ThreadCreator { public static void main(String[] args) { //继承Thread类 new Thread() { @Override public void run() { System.out.println("extends Thread Class!"); } }.start(); //实现Runnable接口 new Thread(new Runnable() { @Override public void run() { System.out.println("implement Runnable!"); } }).start(); //实现Callable接口 new Thread(new FutureTask<Integer>(new Callable() { @Override public Integer call() throws Exception { return 1024; } })).start(); //lambda表达式 new Thread(() -> System.out.println("execute single code")).start(); new Thread(() -> { System.out.println("execute multiple code"); }).start(); } }
lambda thread pool:
public class ThreadCreator { static ExecutorService service = Executors.newFixedThreadPool(5); static List list = new ArrayList(); public static void main(String[] args) { service.execute(() -> execute()); //无返回值 Future future = service.submit(() -> execute()); //有返回值 list.add(future); } public static void execute() { //do something } }
Recommended related article tutorials: java quick start
The above is the detailed content of Summary of how to create threads in java. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Dreamweaver CS6
Visual web development tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment