In the past, everyone wrote single-threaded programs, all calling methods in the main function. You can clearly see that its efficiency is It is particularly low, just like using a single thread to crawl a website in Python, it can be said that it can make you vomit blood because the amount of data is too large. Today we will take a look at the learning of concurrent programming and multi-threading in Java
There are many ways to create a thread, such as inheriting the Thread class and implementing the Runnable interface... Let's take a detailed look at the creation method.
Why inheriting
Thread
can directly call thestart()
method to start the thread, becausestart()
itself is a method of Thread, that is, it inherits the start() method of Thread, so the object of this class can call start() to start the thread
//继承Threadpublic class MyThread extends Thread { public void run() {for (int i = 0; i < 10; i++) { System.out.println(this.getName()+"正在跑"); } } }public class Test{public static void main(String[] args) { Mythread t1=new MyThread(); //创建对象t1.start(); //启动线程} }
Note: Inherit the creation method of the
Thread
class. An object can only create one thread, and multiple threads cannot share one object. Only one thread can correspond to one object, so Let's take a look at the class that implements theRunnable
interface to enable multiple threads to share the same object
//实现Runnable接口public class Demo implements Runnable { @Overridepublic void run() {for(int i=0;i<10;i++) { System.out.println(Thread.currentThread().getName()+"正在跑"); } } }//测试类public class Test{public static void main(String[] args) { Demo d=new Demo(); //创建对象Thread thread1=new Thread(d); //为对象创建一个线程Thread thread2=new Thread(d); //创建另外一个线程//同时启动两个线程thread1.start(); thread2.start(); } }
It can be clearly seen from the above that an object of a class that implements the
Runnable
interface can be shared by multiple threads. It is not as simple as inheriting the Thread class and only using it for one thread.
is created directly in the
main
method. If the object of the ordinary class created is outside, it must be final modified, which allows multiple threads to share an object at the same time. , this is the same as implementing theRunnable
interface. At this time, you need to control the synchronization conditions. If you define an object in the run method, then one thread corresponds to an object, which has the same effect as inheriting the Thread class. So you can freely choose according to the conditions
//普通的一个类public class Simple {public void display() {for(int i=0;i<10;i++) { System.out.println(Thread.currentThread().getName()+"正在跑"); } } }//线程测试类public class Test {public static void main(String[] args) { //如果在外面必须使用final,当然也可以直写在run方法中,不过写在外面可以实现多个线程共享一个对象//写在run方法中当前对象只能为一个线程使用,和继承Thread类一样的效果final Simple simple=new Simple(); //下面创建使用同一个对象创建同两个线程,实现多个线程共享一个对象,和实现Runnable接口一样的效果Thread t1=new Thread(){public void run() { simple.display(); }; }; Thread t2=new Thread(){public void run() { simple.display(); }; }; //启动这两个线程t1.start(); t2.start(); }}
static void sleep(long mils)
Make the running thread sleep for mils milliseconds, but it should be noted here that if the thread is locked, sleeping the thread will not release the lock
String getName()
Get the name of the thread. This method has been used in the above program
void setName(String name)
Set the name of the running thread to name
start()
Start the thread. The creation of the thread does not mean the starting of the thread. Only by calling the start() method can the thread really start running.
long getId()
Returns the identifier of the thread
Use
##run()
The code executed by the thread is placed in the run() method. The calls in the run method are ordered and are executed in the order in which the program runs.
Use the above method to create an instance
//线程的类,继承Threadpublic class MyThread1 extends Thread {public void run() { // 重载run方法,并且在其中写线程执行的代码块for (int i = 0; i < 10; i++) {// 获取线程的id和nameSystem.out.println("Thread-Name: " + this.getName() + " Thread-id: " + this.getId());try {this.sleep(1000); // 线程休眠1秒} catch (InterruptedException e) { e.printStackTrace(); } } } }//线程测试的类public class Test {public static void main(String[] args) { MyThread1 t1 = new MyThread1(); // 创建线程t1.setName("第一个线程"); // 设置线程的名字MyThread1 t2 = new MyThread1(); t2.setName("第二个线程"); t1.start(); // 启动线程,开始运行t2.start(); } }
- ##void join()
Wait for the thread to terminate before running other threads
- void join(long mils)
##UseThe time to wait for the thread is mils milliseconds , once this time has passed, other threads execute normally
//线程类public class MyThread1 extends Thread {public void run() { // 重载run方法,并且在其中写线程执行的代码块for (int i = 0; i < 10; i++) {// 获取线程的id和nameSystem.out.println("Thread-Name: " + this.getName() + " Thread-id: " + this.getId());try {this.sleep(1000); // 线程休眠1秒} catch (InterruptedException e) { e.printStackTrace(); } } } }//测试类public class Test {public static void main(String[] args) { MyThread1 t1 = new MyThread1(); // 创建线程t1.setName("第一个线程"); // 设置线程的名字t1.start(); // 启动线程,开始运行try { t1.join(); //阻塞其他线程,只有当这个线程运行完之后才开始运行其他的线程} catch (InterruptedException e) { e.printStackTrace(); }for (int i = 0; i < 10; i++) { System.out.println("主线程正在运行"); } } }//输出结果/*Thread-Name: 第一个线程 Thread-id: 9Thread-Name: 第一个线程 Thread-id: 9Thread-Name: 第一个线程 Thread-id: 9Thread-Name: 第一个线程 Thread-id: 9Thread-Name: 第一个线程 Thread-id: 9Thread-Name: 第一个线程 Thread-id: 9Thread-Name: 第一个线程 Thread-id: 9Thread-Name: 第一个线程 Thread-id: 9Thread-Name: 第一个线程 Thread-id: 9Thread-Name: 第一个线程 Thread-id: 9主线程正在运行主线程正在运行主线程正在运行主线程正在运行主线程正在运行主线程正在运行主线程正在运行主线程正在运行主线程正在运行主线程正在运行 */
getPriority()
- Get the current thread priority
setPriority(int num)
- Change the priority of the thread (0-10). The default is 5. The higher the priority, the higher the chance of obtaining CPU resources.
Use
//线程类public class MyThread1 extends Thread {public void run() { // 重载run方法,并且在其中写线程执行的代码块for (int i = 0; i < 10; i++) {// 获取线程的id和nameSystem.out.println("Thread-Name: " + this.getName() + " Thread-id: " + this.getId());try {this.sleep(1000); // 线程休眠1秒} catch (InterruptedException e) { e.printStackTrace(); } } } }//测试类public class Test {public static void main(String[] args) { MyThread1 t1 = new MyThread1(); // 创建线程t1.setName("第一个线程"); // 设置线程的名字MyThread1 t2 = new MyThread1(); t2.setName("第二个线程"); t2.setPriority(8); //设置第二个线程的优先级为8,第一个线程的优先级为5(是默认的)t1.start(); t2.start(); } }/* * 从上面的运行结果可以看出大部分的第二个线程都是在第一个线程之前开始执行的,也就是说优先级越高获得cpu执行的几率就越大 * /
setDaemon(boolean)
- Whether to set it as a daemon thread. If it is set to a daemon thread, the daemon thread will also be destroyed when the main thread is destroyed
isDaemon ()
- Determine whether it is a daemon thread
Use
//测试类public class MyThread1 extends Thread {public void run() { // 重载run方法,并且在其中写线程执行的代码块for (int i = 0; i < 10; i++) {// 获取线程的id和nameSystem.out.println("Thread-Name: " + this.getName() + " Thread-id: " + this.getId());try { Thread.sleep(1000); //休眠一秒,方便主线程运行结束} catch (InterruptedException e) { e.printStackTrace(); } } } }public class Test {public static void main(String[] args) { MyThread1 t1 = new MyThread1(); // 创建线程t1.setName("第一个线程"); // 设置线程的名字t1.setDaemon(true); t1.start();for (int i = 0; i < 1; i++) { System.out.println(i); } } }//结果:/* 0123456789Thread-Name: 第一个线程 Thread-id: 9*//* * 从上面的结果可以看出,一旦主线程结束,那么守护线程就会自动的结束 *
The above is the detailed content of The definition and common methods of Thread. For more information, please follow other related articles on the PHP Chinese website!