Let's introduce runnable in this chapter.
1. Example
Package Com.ray.ch17;public class Test {public static void main (string[] args) {for (int i = 5; i < 8; i++) {Donemissio n donemission = new Donemission (i);d onemission.run ();}} Class Donemission implements Runnable {private final int id = index++;p rivate int count = 0;private static int index = 0;p Ublic donemission (int count) {This.count = count;} Public String leftmission () {return "#" + ID + "(" + Count + ")";} @Overridepublic void Run () {while (count--> 0) {System.out.println (leftmission ()); Thread.yield ();}}}
Output:
#0 (4)
#0 (3)
#0 (2)
#0 (1)
#0 (0)
#1 (5)
#1 (4)
#1 (3)
#1 (2)
#1 (1)
#1 (0)
#2 (6)
#2 (5)
#2 (4)
#2 (3)
#2 (2)
#2 (1)
#2 (0)
The output is in order.
Explain:
(1) The above code, although written as a multi-threaded look, but in the call is not through the multi-threaded call.
(2) Implement runnable interface to be able to use multithreading
(3) ID is final and is used to mark the ID of each object
(4) Count refers to the number of tasks
(5) The Meaning of Thread.yield () is: I am here the task has been completed phased, you can switch to other contexts.
2. Convert the above code to use multi-threaded
Package Com.ray.ch17;public class Test {public static void main (string[] args) {for (int i = 5; i < 8; i++) {Donemissio n donemission = new donemission (i); Thread thread = new Thread (donemission); Thread.Start ();}}} Class Donemission implements Runnable {private final int id = index++;p rivate int count = 0;private static int index = 0;p Ublic donemission (int count) {This.count = count;} Public String leftmission () {return "#" + ID + "(" + Count + ")";} @Overridepublic void Run () {while (count--> 0) {System.out.println (leftmission ()); Thread.yield ();}}}
Output:
#0 (4)
#1 (5)
#1 (4)
#1 (3)
#1 (2)
#2 (6)
#0 (3)
#2 (5)
#2 (4)
#2 (3)
#1 (1)
#1 (0)
#2 (2)
#2 (1)
#2 (0)
#0 (2)
#0 (1)
#0 (0)
The output is messy because the switch between tasks is determined by the cup.
Explain:
(1) When you need to use multithreading, you need to define the thread object.
(2) The thread object needs to call the Start method.
Summary: This section briefly describes the runnable.
This chapter is here, thank you.
-----------------------------------
Directory
Learn java-17.2 basic threading mechanism from the beginning (1)-Initial runnable