How to use Thread class in Java and what are its attributes
WBOY
Release: 2023-05-14 09:07:16
forward
1606 people have browsed it
Multi-threaded programming can be performed in java. A Thread class is provided in the java standard library to represent thread operations. The Thread class can be regarded as a set of APIs provided by the Java standard library to solve multi-threaded programming.
The created Thread instance corresponds one-to-one to the threads in the operating system. The operating system provides an API (C language style) about threads, and Java encapsulates it into the Thread class.
Create a thread
Method 1: Inherit the Thread class
class MyThread extends Thread{
@Override
public void run() {
//此时只是定义处理一个线程类,在系统中总是还没有创建出 新的线程。
System.out.println("hello thread");
}
}
public class TestDemo11 {
public static void main(String[] args) {
//创建线程
Thread t = new MyThread();
//启动线程,在系统中创建出了新的线程
t.start();
}
}
Copy after login
Threads are executed concurrently
class MyThread3 extends Thread{
@Override
public void run() { //定义一个线程类
while (true) {
System.out.println("hello thread");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
public class TestDemo13 {
public static void main(String[] args) {
Thread t = new MyThread3();
t.start();//启动t线程
while(true){
System.out.println("hello main");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
Copy after login
##We can see that
1s enters the blocking state after executing the code in a thread, then the next Which thread should be awakened in seconds? We can see that the order of the logs printed in the two executed threads is uncertain. In each round, after 1s, it is uncertain whether to wake up the thread thread or the main thread. (Preemptive execution). For the operating system, the order in which threads are scheduled is macroscopically random.
Here we will explain the Thread.sleep() method and the sleep() method. It's not that precise at the ms level. When this method is called, the thread is forced to be in a medium blocking (sleep state), but when the blocking time is over, the thread will not continue to execute on the cup immediately. If Thread.sleep(1000), after 1s passes, the blocking time will Ends, but at 1001ms, the thread may not execute immediately. Maybe the cup in the operating system is busy with other threads. Maybe the thread is executed at 1006ms.
Method 2: Implement the run() method in the Runnable interface
//Runnable其实就是描述一个任务
//创建一个类,实现Runnable接口,重写Runnable类中的run方法,在run()方法中,描述的是该线程要指向的哪些任务。
class MyThread2 implements Runnable{
@Override
public void run() {
System.out.println("hello thread");
}
}
public class TestDemo12 {
public static void main(String[] args) {
//创建线程,把创建好的Runnable实例传给Thread实例
Thread t = new Thread(new MyThread2());
t.start();
}
}
Copy after login
Method 3: Use internal classes
Method 3 is actually one method A remake is to change the above two codes into anonymous inner classes.
public class TestDemo14 {
public static void main(String[] args) {
Thread t1 = new MyThread(){
@Override
public void run() {
System.out.println("hello thread1");
}
};
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("hello thread2");
}
});
t1.start();
t2.start();
}
}
Copy after login
Method 4: Use lambmd expression
public class TestDemo15 {
public static void main(String[] args) {
//其实就是使用lambad表达式代替Runnable
Thread t1 = new Thread(()->{
//()表示无参的run()方法
System.out.println("hello thread1");
});
}
}
Copy after login
Benefits of using threads
In order to more conveniently reflect multiple The benefit of threads is that here we start from 0 and increment by 1 until it reaches 10_0000_0000. We use the serial method and the parallel method, and get the time they execute the code for comparison.
public class TestDemo16 {
public static void func1() throws InterruptedException {
long big = System.currentTimeMillis();
//串行执行
Thread t = new Thread(()->{
long a = 0;
for(long i = 0;i<10_0000_0000;i++){
a++;
}
});
t.start();
t.join();
long end = System.currentTimeMillis();
System.out.println("串行消耗时间:" + (end - big) + "ms");
}
public static void func2() throws InterruptedException {
long big = System.currentTimeMillis();
Thread t1 = new Thread(()->{
long b = 0;
for(long i = 0;i< 10_0000_0000 / 2;i++){
b++;
}
});
t1.start();
Thread t2 = new Thread(()->{
long c = 0;
for(long i = 0;i<10_0000_0000/ 2;i++){
c++;
}
});
t2.start();
t1.join();
t2.join();
long end = System.currentTimeMillis();
System.out.println("并行执行消耗时间:" + (end - big) + "ms");
}
public static void main(String[] args) throws InterruptedException {
func1();//串行执行
func2();//并行执行
}
}
Copy after login
We can clearly see that the serial time is much longer than the parallel time. The serial time is almost twice the parallel time.
public class TestDemo18 {
public static void main(String[] args) {
Thread t = new Thread(()->{
System.out.println("hello thread");
});
t.start();
System.out.println(t.isDaemon());
}
}
//因为我们创建的是一个前台线程,所以返回false
public class TestDemo22 {<!--{C}%3C!%2D%2D%20%2D%2D%3E--> public static void main(String[] args) throws InterruptedException {<!--{C}%3C!%2D%2D%20%2D%2D%3E--> Thread t = new Thread(()->{<!--{C}%3C!%2D%2D%20%2D%2D%3E--> for(int i = 0;i<5;i++){<!--{C}%3C!%2D%2D%20%2D%2D%3E--> System.out.println("hello thread"); try {<!--{C}%3C!%2D%2D%20%2D%2D%3E--> Thread.sleep(1000); } catch (InterruptedException e) {<!--{C}%3C!%2D%2D%20%2D%2D%3E--> e.printStackTrace(); } } }); t.start(); t.join();//main线程调用t.join()方法,main线程就处于阻塞状态,当t线程执行完后,唤醒main线程执行后序代码 System.out.println("hello main"); }}
Copy after login
获取线程的引用
使用方法Thread.currentTread()就可以该线程的实例。
public class TestDemo23 {
public static void main(String[] args) {
Thread t = new Thread(){
@Override
public void run() {
//获取当前线程的引用
//System.out.println(Thread.currentThread().getName());
//因为当前使用的匿名内部类是继承自Thread类,Thread就是该匿名内部类的父类,所以可以通过this得到当前Thread的实例
System.out.println(this.getName());
}
};
t.start();
}
}
The above is the detailed content of How to use Thread class in Java and what are its attributes. For more information, please follow other related articles on the PHP Chinese website!
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn