Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to set priority for Java multithreading

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article introduces the knowledge of "how to set priority for Java multithreading". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!

Examples are as follows:

We know that aircraft flying in the sky has a fixed route (can be understood as threads), and each airport has the maximum operating load capacity. When the operation exceeds the load capacity, this requires the participation of tower dispatching. Will be sorted according to the priority of each aircraft. When on the route, if there is an emergency, other aircraft will be allowed to avoid, so that the aircraft priority is raised, landing first. This is scheduling, and so is the running of computer programs.

1. Scheduling of threads:

In Java multithreading, there are four main ways to allocate the right to use CPU:

Set priority (Priority) sets the priority of the thread, with a value of 1-10

Sleep units of milliseconds, so that this thread belongs to the blocking state, CPU will execute other threads

Force join to force this thread to get CPU resources to run

Yield pauses the executing thread to let other threads execute first, and then executes after execution.

1. Set priority (Priority):

There are two threads that set the maximum priority and the minimum priority, respectively:

Public class MyThread implements Runnable {@ Override public void run () {for (int I = 0; I)

< 5; i++) { System.out.println(Thread.currentThread().getName()+"正在运行:"+i); } } public static void main(String[] args) { Thread t1 = new Thread(new MyThread(),"线程A:"); Thread t2 = new Thread(new MyThread(),"线程B***:"); //设置优先级: 最高为10 最低为1 t1.setPriority(Thread.MAX_PRIORITY); t2.setPriority(Thread.MIN_PRIORITY); //显示线程优先级: System.out.println("线程A的优先级是:"+t1.getPriority()); System.out.println("线程B的优先级是:"+t2.getPriority()); t1.start(); t2.start(); }} 结果:

2. Dormancy (sleep)

Thread.sleep ();-in milliseconds, so that this thread is in a blocking state, and CPU executes other threads:

Public class ThreadSleep {public static void main (String [] args) {sleepTime (5);} private static void sleepTime (int time) {for (int I = 0; I)

< 5; i++) { System.out.println("主线程执行了:"+i+"s"); try{ //让线程休眠,进入阻塞状态 Thread.sleep(1000); //休眠时间为1000毫秒 } catch (InterruptedException e) { e.printStackTrace(); } } }} 结果:

3. Force operation (join)

As the name implies, it forces a thread into execution:

Child threads:

Public class MyThread {}

Test class:

Public class Test {public static void main (String [] args) throws InterruptedException {Thread T1 = new Thread (new MyThread (), "I am a child thread"); t1.start (); / / when the main thread executes task 1-10:00, force child thread T1 to execute if it reaches 5, and do not let the main thread continue to execute task for (int I = 0; I) until it is finished.

< 6; i++) { if (i==2){ t1.join(); } System.out.println(Thread.currentThread().getName()+"正在运行:"+i); } }} 结果: 4、礼让(yield) 暂停正在执行的线程,让其他线程先执行,执行完了在接着执行: public class MyThread implements Runnable{ //线程礼让,让本线线程阻塞,其他线程先执行 //这里就是A线程运行二次后,礼让,让B 线程先执行 //也是理论上的,就是不管怎么样第二次后面肯定让B先执行,但是后面就随机了 @Override public void run() { for (int i = 0; i < 5; i++) { System.out.println(Thread.currentThread().getName()+"正在运行:"+i); if(i == 2){ Thread.yield(); } } }} 测试类: public class Test { public static void main(String[] args) { Thread t1 = new Thread(new MyThread(),"线程A:"); Thread t2 = new Thread(new MyThread(),"----线程B"); t1.start(); t2.start(); }} 结果: 2、定时器线程: 定时器就是可以设置某个时间点来执行某个事件,比如系统每周删除依次日志文件,或者在指定的日期关闭系统,定时器本身就是一个线程任务来在指定的时候执行该任务。定时器是继承TimerTask来重写run方法,专门处理定时任务。 演示Demo: public class MyThread extends TimerTask { @Override public void run() { //把任务定义在run方法中 showMyself(); } public void showMyself(){ System.out.println("被Run方法执行的"); }} 测试类: public class Test { public static void main(String[] args) { Timer timer = new Timer(); //设置5秒后执行这个任务,并且每1秒重复执行这个任务 timer.schedule(new MyThread(),5000,1000); }} 结果: 3、线程的同步: 首先我们先看一个demo: 创建了两个线程对象,一个线程A任务用于执行print1,另一个线程B任务用于执行print2: public void print1(){ System.out.print("中"); System.out.println("国"); } public void print2(){ System.out.print("浙"); System.out.println("江"); }} 测试类: public class Test { public static void main(String[] args) { Printer p = new Printer(); //A: new Thread(new Runnable() { @Override public void run() { while(true){ p.print1(); } } },"线程A:").start(); //B: new Thread("线程B:"){ @Override public void run(){ while (true){ p.print2(); } } }.start(); }} 这个程序就是当线程A执行的时候,输出中国,当B执行的时候,输出浙江,理论上是没有任何问题,但是我们看一下结果: 我们发现出问题了,其实这就是非线程同步(异步): 同步:提交请求->

Wait for the server to process-> the client browser cannot do anything during the period when it is returned after processing.

Async: request triggered by event-> server processing (this is where browsers can still do other things)-> finished processing

In fact, non-thread synchronization is a very dangerous problem in some systems, such as 12306, if you use non-thread synchronization, then the consequences can be imagined, so how to synchronize? Here is a common way to lock:

If both ends of the code (two thread tasks) are synchronized, then CPU can only execute one task at a time, which is equivalent to putting a lock on the thread. When the thread does not finish executing the code or task, other threads cannot use CPU resources to execute the task. Other threads cannot execute until the code for the thread has been executed.

Better understanding (for example):

You go to the public toilet (big), when you go in, you need to close the door and lock it, which is locked, in order to ensure your normal end (to ensure that the thread is running properly), no one else can come in during this period.

Synchronized lock:

If two thread tasks use the same object as a lock, then the two thread methods are synchronized. Let's put a lock on the above method:

Class Demo {} public class Printer {/ / create any object, as long as the object is the same, the lock is the same, it is synchronous! Demo d = new Demo (); public void print1 () {/ / when entering the print1 method, synchronized gives the method a lock synchronized (d) {System.out.print ("medium"); System.out.println ("country") }} public void print2 () {/ / when entering the print2 method, synchronized also puts a lock on the method synchronized (d) {System.out.print ("Zhejiang"); System.out.println ("Jiang");}

In this way, the above problem will not appear after the output, and the screenshot of the result will not be sent here. You can try for yourself to see if this problem has been solved.

We can also define locks directly on methods, such as this:

Public static synchronized void print1 () {System.out.print (medium); System.out.println (country);}

If it is a static method, it is locked through a .class bytecode object:

Public static void print1 () {synchronized (Printer.class) {System.out.print (medium); System.out.println (country);}}

This is the end of the content of "how to set priority for Java multithreading". Thank you for reading. If you want to know more about the industry, you can follow the website, the editor will output more high-quality practical articles for you!

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.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report