1. Introduction
Threads enable the program to have two and more than two executable paths, especially for multicore CPUs.
2. Create a thread
1. Inheriting the thread class
If a class inherits the thread class directly, this class has the ability of threading, and the next step is to rewrite the inherited run ().
<span style= "FONT-SIZE:18PX;" >package com. thread;//defines a class that implements the Runnable interface MyThread11 extends thread{//implements the Run method, specifying the task that the thread executes public void run () {System.out.println (" Start a thread! ");}} Main class public class Sample16_2{public static void Main (string[] args) {//Inherit thread's class to create threading object Threads t=new MyThread11 (); Start thread T.start (); SYSTEM.OUT.PRINTLN ("thread Enabled");}} </span>
2. Implement the Runnable interface
Java uses the single inheritance, if inheriting the thread class, there will be a lot of restrictions, so it is often used to inherit the runnable interface to implement thread creation.
<span style= "FONT-SIZE:18PX;" >package com. thread;//defines a class that implements the Runnable interface Myrunnable implements runnable{//implements the Run method, specifying the task that the thread executes public void run () { System.out.println ("Congratulations, the thread is started," + "executes the code in the Run Method!!! ");}} Main class public class Sample16_1{public static void Main (string[] args) {//Create object for class that implements Runnable interface myrunnable mr=new myrunnable () ;//Create a thread object, take the first step to create a reference to the object as a constructor parameter//pass, specify the task the thread is to perform thread t=new thread (MR);//Start thread t.start (); SYSTEM.OUT.PRINTLN ("thread Enabled");}} </span>
3. Synchronization of Threads
1. Synchronization method
Synchronous method refers to the method that uses the Synchronized keyword adornment, the thread that enters the synchronous method executes will obtain the lock of the object that the synchronous method belongs to, once locked, only then the thread executes, the other thread can execute, thus guaranteed the security of the method synchronization.
<span style= "FONT-SIZE:18PX;" >package com. thread;//resource Classes class resource{synchronized void Function1 (Thread currthread) {System.out.println (Currthread.getname () + "Thread execution Function1 Method!!!" "); Try{thread.sleep (1000); System.out.println (Currthread.getname () + "thread wakes up!!!" ");} catch (Exception e) {e.printstacktrace ();}} synchronized void function2 (thread currthread) {System.out.println (Currthread.getname () + "Thread execution Function2 Method!!! ");}} Custom threading Class MyThread00 extends thread{//resource object reference Resource rs;//constructor public MyThread00 (String Tname,resource rs) { This.setname (tname); this.rs=rs;} public void Run () {if (This.getname (). Equals ("Thread1")) {//If the thread name is a function1 method that Thread1 accesses the resource rs.function1 (this);} else{//if the thread name is not a Thread1 access resource function2 method System.out.println ("Thread2 startup, waiting to enter the synchronization method function2!!! "); Rs.function2 (this);}}} Main class public class Sample16_8{public static void Main (String args[]) {Resource rs=new Resource (); MyThread00 t1=new MyThread00 ("Thread1", RS); MyThread00 t2=new MyThread00 ("Thread2", RS); T1.start (); Try {thread.sleep (10); } catch (Exception e) {e.printstacktrace ();} T2.start ();}} </span>
Note: An object can have synchronous and non-synchronous methods, only to enter the synchronous method of execution to obtain a lock, each object has only one lock; If an object has multiple synchronized methods, when one of the threads accesses one of them, the other thread cannot access any of the synchronization methods of the object's focus amount If the thread gets a lock and enters sleep or concessions, it will sleep or give in with a lock.
2. Synchronizing statement blocks
Using the synchronous block of statements can improve the concurrency of the program, and can accurately determine the region of synchronization.
<span style= "font-size:18px;" >package com. thread;//custom thread class MyThread33 extends thread {//The reference is a resource object private object resource;//no parameter constructor public MyThread33 () {}// The constructor public MyThread33 (Object resource,string name) {//initializes the thread This.resource=resource;this.setname (name);} public void Run () {////Synchronous statement block synchronized (Resource) {System.out.println (This.getname () + "thread accesses the resource!!! "); System.out.println (This.getname () + "thread with the lock went to sleep!!!" "); try {thread.sleep (1000); } catch (Exception e) {e.printstacktrace (); } System.out.println (This.getname () + "thread with a lock woke up after releasing the lock!!! ");}}} Main class public class Sample16_10{public static void Main (string[] args) {//Create Resource Object Objects resource=new ();// Create 2 threads MyThread33 mt1=new MyThread33 (Resource, "MT1"); MYTHREAD33 mt2=new MyThread33 (Resource, "MT2");//Start these 2 threads Mt1.start (); Mt2.start ();}} </span>
Note: where synchronized (XXX), XXX represents a reference to a resource object.
4. Other Settings for threads
1. Priority of Threads
The priority of a thread in Java is expressed as an integer between 1 and 10, and the higher the value the higher the priority, the greater the chance of gaining access to the CPU. Generally use the SetPriority method to set.
<span style= "FONT-SIZE:18PX;" >package com. thread;//definition inherits the thread's class MyThread1 extends thread {//Overrides the Run method, specifies that the thread executes code public void run () {for (int i = 0; I <=; i + +) {System.out.print ("<min" + i + ">");}}} Define another class that inherits the thread classes MyThread2 extends Thread {//Overrides the Run method, specifying that the thread executes code public void run () {for (int i = 0; I <=; i++ {System.out.print ("[Max" + i + "]");}}} Main class public class Sample16_4 {public static void main (string[] args) {//Create two thread objects MyThread1 t1 = new MyThread1 (); MyThread2 t2 = new MyThread2 ()//Set priority of two threads t1.setpriority (thread.min_priority); T2.setpriority (thread.max_priority) ;//Start two threads T1.start (); T2.start ();}} </span>
2. Concession of threads
In the actual development sometimes also need to let a thread out of the CPU, so that other threads proud to execute, this time can take concessions to operate. The yield method is generally called.
<span style= "FONT-SIZE:18PX;" >package com. thread;//defines a Runnable implementation class class MyRunnable1 implements runnable{//declares two strings that identify the thread private string Flagl;private string Flagr ;//myrunnable constructor Public MyRunnable1 (String flagl,string flagr) {//Initialize identity string This.flagl=flagl;this.flagr=flagr;} Override the Run method to specify that the thread executes code public void run () {for (int i=0;i<30;i++) {System.out.print (FLAGL+I+FLAGR);// Call the yield method to make the currently executing thread concession thread.yield ();}}} Main class public class Sample16_5{public static void Main (string[] args) {//Create two objects that implement Runnable interface classes MyRunnable1 mr1=new MyRunnable1 ("[", "]"); MyRunnable1 mr2=new MyRunnable1 ("<", ">");//Create two Threads thread object and specify Targetthread t1=new thread (MR1) to execute; Thread t2=new thread (MR2);//start thread T1, T2t1.start (); T2.start ();}} </span>
5. Summary
This article briefly summarizes some of the concepts in threading, but these concepts are a prerequisite for developing advanced threads in the future and require more understanding.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Java Learning Note Five (multithreading)