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

What are the ways to create Java threads

2025-04-01 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article introduces you what Java thread creation methods are, the content is very detailed, interested friends can refer to, hope to be helpful to you.

The creation of multithreading, way 1: inherit from Thread class

1. Create a subclass that inherits from the Thread class

two。 Override run () of the Thread class-> declare the operation performed by this thread in run ()

3. Create an object of a subclass of the Thread class

4. Call start () through this object:

The two functions of the start () method:

a. Start the current thread

b. Call the run () of the current thread

Two issues in the creation process:

Problem 1: we cannot start a thread by calling run () directly

Problem 2: when starting a thread and traversing an even number, you can't let the thread that has already start () execute, it will report an exception; the correct way is to recreate the object of a thread.

/ / 1. Create a subclass class MyThread extends Thread {/ / 2 that inherits from the Thread class. Override the run () @ Override public void run () of the Thread class {/ / the second thread for (int I = 0 position I)

< 10;i++){ if(i % 2 == 0){ System.out.println(i); } } }}public class ThreadTest { public static void main(String[] args) {//主线程 //3.创建Thread类的子类的对象 MyThread t1 = new MyThread(); //4.通过此对象调用start() t1.start(); //问题一:不能通过直接调用run()的方式启动线程// t1.run();//错误的 //问题二:再启动一个线程:我们需要再创建 一个对象 //t1.start();//错误的 MyThread t2 = new MyThread(); t2.start(); for(int i = 0;i < 10;i++){ if(i % 2 != 0){ System.out.println(i + "****main()******"); } } }} 此代码在主线程内输出奇数,在另一个线程里输出偶数,则输出结果应该是两个输出结果是交互的。 1****main()****** 3****main()****** 5****main()****** 7****main()****** 0 2 4 6 8 9****main()****** class Window extends Thread{//创建三个窗口卖票, 总票数为100张,使用继承于Thread类的方式 private static int ticket = 100;//三个窗口共享:声明为static @Override public void run() { while(true){ if(ticket >

0) {System.out.println (getName () + ": ticket number:" + ticket); ticket--;} else {break;} public class WindowTest2 {public static void main (String [] args) {Window T1 = new Window (); Window T2 = new Window () Window T3 = new Window (); t1.setName ("window 1"); t2.setName ("window 2"); t3.setName ("window 3"); t1.start (); t2.start (); t3.start ();} public class ThreadDemo {public static void main (String [] args) {/ / MyThread1 M1 = new MyThread1 () / / MyThread2 m2 = new MyThread2 (); / / m1.start (); / / m2.start () / / since the created class has only created an object once, it will not be used later. You can consider using anonymous classes / / creating anonymous subclasses of the Thread class new Thread () {@ Override public void run () {for (int I = 0bot I).

< 100;i++){ if(i % 2 == 0){ System.out.println(i); } } } }.start(); new Thread(){ @Override public void run() { for(int i = 0;i < 100;i++){ if(i % 2 != 0){ System.out.println(i); } } } }.start(); }}class MyThread1 extends Thread{ @Override public void run() { for(int i = 0;i < 100;i++){ if(i % 2 == 0){ System.out.println(i); } } }}class MyThread2 extends Thread{ @Override public void run() { for(int i = 0;i < 100;i++){ if(i % 2 != 0){ System.out.println(i); } } }} 创建多线程的方式二:实现Runnable接口 创建一个实现了Runnable接口的类 实现类去实现Runnable中的抽象方法:run() 创建实现类的对象 将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象 通过Thread类的对象调用start() class MThread implements Runnable{ //2.实现类去实现Runnable中的抽象方法:run() @Override public void run() { for(int i = 0;i < 100;i++){ if (i % 2 == 0) { System.out.println(Thread.currentThread().getName() + ":" + i); } } }}public class ThreadTest1 { public static void main(String[] args) { //3.创建实现类的对象 MThread mThread = new MThread(); //4.将此对象作为参数传递到Thread类的构造器中,创建Thread类的对象 Thread t1 = new Thread(mThread); t1.setName("线程1"); //5.通过Thread类的对象调用start():A.启动线程B.调用当前线程的run()-->

Call target t1.start () of type Runnable; / / start another thread to traverse an even number within 100s / / simply re-implement step 4 new Thread 5 to Thread T2 = new Thread (mThread); t2.setName ("Thread 2"); t2.start () }} class window1 implements Runnable {/ / create three windows to sell tickets with a total number of 100. using the way to implement the Runnable interface, private int ticket = 100; Object obj = new Object (); @ Override public void run () {while (true) {if (ticket > 0) {System.out.println (Thread.currentThread (). GetName () + "sell tickets, ticket number:" + ticket) Ticket--;} else {break;} public class WindowTest {public static void main (String [] args) {window1 w = new window1 (); / / only one object is created, so 100 tickets share Thread T1 = new Thread (w); Thread T2 = new Thread (w) Thread T3 = new Thread (w); t1.setName ("Thread 1"); t2.setName ("Thread 2"); t3.setName ("Thread 3"); t1.start (); t2.start (); t3.start ();} the third way to create a thread: implement the Callable interface-add JDK5.0

Callable is more powerful than using Runnable

Compared to the run () method, you can have a return value

Method can throw an exception

Return values that support generics

> you need to use the FutureTask class, such as getting the returned result

Future interface

> you can cancel the execution results of specific Runnable and Callable tasks, query whether they are completed, obtain the results, and so on.

FutureTask is the only implementation class of the Futrue interface

> FutureTaskb also implements the Runnable,Future interface. It can be executed by the thread either as Runnable or as Future to get the return value of Callable

/ / 1. Create an implementation class class NumThread implements Callable {/ / 2 that implements Callable. Implement the call method by declaring the operations that this thread needs to perform in call () @ Override public Object call () throws Exception {int sum = 0; for (int I = 1 JDK5.0 added

Background: frequently created and destroyed, heavily used resources, such as threads in concurrency, have a significant impact on performance.

Idea: create many threads in advance, put them into the thread pool, get them directly when you use them, and put them back into the pool after use. Frequent creation and destruction can be avoided and reuse can be achieved. Similar to public transport in daily life.

Benefits: > improved response time (reduces the time to create new threads)

Reduce resource consumption (reuse threads in the thread pool and do not need to create them every time)

> convenient for thread management: A.corePoolSize: the size of the core pool B.maximumPoolSize: maximum number of threads C.keepAliveTime: how long will the thread terminate after it has no task?

Class NumberThread implements Runnable {@ Override public void run () {for (int I = 0bot I) ignore this method if there are no threads of the same priority in the queue

7.join (): call the join () of thread b in thread a, and thread an enters the blocking state (stop execution), and thread b does not end the blocking state (start execution) until thread b has finished its full execution.

8.sleep (long millitime): lets the current thread "sleep" the specified millitime milliseconds. The current thread is in a blocking state for the specified millitime millisecond. An InterruptedException exception is thrown

* 9.isAlive (): determines whether the current thread is alive or not

Class HelloThread extends Thread {@ Override public void run () {for (int I = 0 per I)

< 100;i++){ if(i % 2 != 0){ try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName() + ":" +Thread.currentThread().getPriority() + ":" + i); } } } public HelloThread(String name){ super(name); }}public class ThreadMethodTest { public static void main(String[] args) { HelloThread h2 = new HelloThread("Thread:1");//通过构造器给线程命名,但前期是得在子类中提供一个构造器// h2.setName("线程一"); //设置分线程的优先级 h2.setPriority(Thread.MAX_PRIORITY); h2.start(); //给主线程命名 Thread.currentThread().setName("主线程"); Thread.currentThread().setPriority(Thread.MIN_PRIORITY); for(int i = 0;i < 100;i++){ if(i % 2 == 0) { System.out.println(Thread.currentThread().getName() + ":" + Thread.currentThread().getPriority() + ":" + i); }// if(i == 20){// try {// h2.join();//join()的测试// } catch (InterruptedException e) {// e.printStackTrace();// }// } } }}线程的优先级: 1.MAX_PRIORITY:10 MIN_PRIORITY:1 NORM_PRIORITY:5--->

Default priority

two。 How to get and set the priority of the current thread:

GetPriority (): gets the priority of the thread

SetPriority (int p): sets the priority of a thread

Description: the high-priority thread wants to preempt the execution power of the low-priority thread CPU, but only in terms of probability, when the high-priority thread has a high probability, it does not necessarily be executed, which does not mean that the low-priority thread executes only when the high-priority thread finishes execution.

About the way Java thread creation has been shared here, I hope the above content can be of some help to you, you can learn more knowledge. If you think the article is good, you can share it for more people to see.

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