In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-02-26 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "the basic usage course of Java thread". The content of the explanation in the article is simple and clear, and it is easy to learn and understand. let's study and learn the basic usage course of Java thread together.
Thread thread and process
The process is the smallest unit of resources allocated by the operating system, while the thread is the smallest unit of program execution, and they can be executed concurrently. A process has at least one thread that shares the resource space of the process.
Introduction to Thread
Each thread has a priority, and the high-priority thread executes before the low-priority thread. Priority values range from 1 to 10, and the default is 5. Each thread may be marked as a daemon thread. When a thread creates another new thread object, the priority of the new thread is equal to the priority of the thread that created it; if the new thread object is a daemon thread if and only if the thread that created it is a daemon thread.
Thread classification
Java threads are divided into daemon threads (Daemon Thread) and user threads (User Thread). The daemon thread and the user thread are basically the same, the only difference is that if the user thread exits, the virtual machine will exit with or without the daemon thread. The role of a daemon thread is to provide services for other threads to run. The most typical daemon thread is GC (garbage collection period).
Create a thread the way a thread is created
There are three ways to create a thread class:
Inherit the Thread class
Implement the Runnable interface
Implement the Callable interface
Introduction to ThreadThread
Thread is the most critical class for creating threads, and the word itself stands for threads, and the Thread class implements the Runnable interface.
Code example public class ThreadDemo extends Thread {public void run () {for (int I = 0; I
< 60; i++) { System.out.println(getName() + ":" + i); } }}public class Demo{ public static void main(String[] args) { ThreadDemo t1 = new ThreadDemo(); ThreadDemo t2 = new ThreadDemo(); t1.start(); t2.start(); }}RunnableRunnable简介 Runnable是提供线程的接口,有一个抽象方法public abstract void run()。实现了这个接口的类必须实现它的run方法。 代码示例public class Runnable implements Runnable{ public void run() { public void run() { for (int i = 0; i < 60; i++) { System.out.println(Thread.currentThread().getName() + ":" + i); } } }}public class Demo{ public static void main(String[] args) { RunnableDemo run = new RunnableDemo(); Thread t1 = new Thread(run); Thread t2 = new Thread(run); t1.start(); t2.start(); }}Callable和FutureCallable和Future简介 Thread和Runnable创建线程不能获取线程的返回值。从Java1.5开始,就提供了Callable和Future,通过他们可以在任务执行完毕之后得到任务执行结果。 Callable接口:可以返回一个结果或者抛出一个异常的一个任务,实现者定义一个没有参数的call方法。区别于Thread和Runnable的run方法,Calllable任务执行的方法是call。 Future接口:Future接口代表了异步计算的结果,提供了一些方法用于检查计算结果是否完成,获取计算结果等。FutureTask类提供了Future接口的实现,并且实现了Runnable接口。 代码案例public class MyCallable implements Callable { public Integer call() { int sum = 0; for (int i = 0; i { synchronized (demo) { System.out.println("t1 start"); try { demo.wait(); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("t1 end"); } }); Thread t2 = new Thread(() ->{synchronized (demo) {System.out.println ("T2 start"); System.out.println ("T2 end"); demo.notify ();}}); t1.start (); t2.start ();}}
Join method
Belongs to the Thread class, the join method blocks the thread calling this method, and when thread a calls thread b's b.join (long), thread a blocks until thread b finishes execution.
Public class Demo {public static void main (String [] args) throws Exception {System.out.println ("main start"); Thread T1 = new Thread (()-> {System.out.println ("T1 start"); System.out.println ("T1 end");}); t1.start (); t1.join (); System.out.println ("main end") }}
Park method
Belongs to the LockSupport class, LockSupport is a thread blocking utility class, all methods are static methods, you can use the park method to block the thread, use unpart to wake up the thread.
Public class Demo {public static void main (String [] args) {System.out.println ("main start"); Thread T1 = new Thread (()-> {System.out.println ("T1 start"); LockSupport.park (); System.out.println ("T1 end");}); t1.start (); LockSupport.unpark (T1) System.out.println ("main end");}}
Running status & timeout waiting
Call the Object.wait (long); Thread.join (long); LockSupport.park (long) method to take the thread from the running state to the waiting state until it reaches the waiting time or wakes up actively.
Wait (long) method
Belongs to the Object class, when the object calls wait (long), the thread that currently holds the object lock releases the current object lock and enters the waiting queue until the waiting time is reached or the object calls notify or notifyall to wake up the thread from the waiting queue, and the thread starts competing for the lock again.
Public class Demo {public static void main (String [] args) {Demo demo = new Demo (); Thread T1 = new Thread (()-> {synchronized (demo) {for (int I = 0; I)
< 1000; i++) { if (i == 500) { try { demo.wait(100); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println("------t1------: " + i); } } }); Thread t2 = new Thread(() ->{synchronized (demo) {for (int I = 0; I)
< 1000; i++) { System.out.println("------t2------: " + i); } } }); t1.start(); t2.start(); }} join(long)方法 是属于Thread类的,join(long)方法是阻塞调用此方法的线程,当线程a调用线程b的b.join(long),线程a会阻塞直到到达阻塞时间或者线程b执行完成。 public class Demo { public static void main(String[] args) throws Exception { System.out.println("main start"); Thread t1 = new Thread(() ->{for (int I = 0; I)
< 1000; i++) { System.out.println("----t1----: " + i); } }); t1.start(); t1.join(1); System.out.println("main end"); }} parkUntil(long)和parkNanos(long) 是属于LockSupport类的,LockSupport是一个线程阻塞工具类,所有的方法都是静态方法,可以使用parkUntil(long)和parkNanos(long)方法来阻塞线程。parkNanons是阻塞long时间,parkUntil是阻塞截止到long时间。 public class Demo { public static void main(String[] args) { System.out.println("main start"); Thread t1 = new Thread(() ->{System.out.println ("T1 start"); LockSupport.parkNanos (300000000L); System.out.println ("T1 end");}); t1.start (); System.out.println ("main end");}} public class Demo {public static void main (String [] args) throws Exception {System.out.println ("main start") Thread T1 = new Thread (()-> {System.out.println ("T1 start"); String dateTimeStr = "2021-04-04 14:57:00"; DateTimeFormatter df = DateTimeFormatter.ofPattern ("yyyy-MM-dd HH:mm:ss"); LocalDateTime dateTime = LocalDateTime.parse (dateTimeStr, df); LockSupport.parkUntil (dateTime.toInstant (ZoneOffset.of ("+ 8")). ToEpochMilli ()) System.out.println ("T1 end");}); t1.start (); System.out.println ("main end");}} infinite wait & blocking state
The thread will enter the infinite waiting state after the object calls the wait method, and when the object calls notify or notifyAll, the thread will enter the blocking state from the infinite waiting state.
Blocking state to running state
The thread is in a blocking state, and if the lock object is acquired, it will enter the running state.
Thank you for reading, the above is the content of the basic usage course of Java thread, after the study of this article, I believe you have a deeper understanding of the basic usage tutorial of Java thread, and the specific usage needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.