Home >Java >javaTutorial >Introduction to the understanding and use of multi-threading
1. Word part:
①process ②current current ③thread thread ④runnable available
⑤interrupt ⑥join join ⑦yield generated ⑧synchronize occurs simultaneously
2. Preview part
1. The difference between threads and processes:
The process is the basic unit of the system running program
The thread is the smallest unit for performing operations in the process
2 .Explain what are the two ways to create a thread
①Inherit the thread class
②Implement the Runnable interface
3. The life cycle of a thread can be divided into several stages, each What are the stages?
Five stages: ① Create ② Ready ③ Run ④ Block ⑤ Death
4. What method of thread can be used to set the sleep of the thread, the forced execution of the thread, and the courtesy of the thread?
They are: sleep(),join(),yield()
5. Under what circumstances is it necessary to synchronize threads? There are several ways to synchronize threads
When access conflicts occur,
need to be done in two ways: ① Synchronization method ② Synchronization code block
3. Practice part
1. Create a thread using a method that inherits the Thread class, Display the corresponding content
First create a thread class:
package oneOne;
public class MyRunnableone extends Thread{
public void run() {
for(int i=1;i<=20;i++){
System.out.println(i+".Hello, from thread"+Thread.currentThread().getName());
}
}
}
Create the main method class again and remove it
package oneOne;
public class testone {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyRunnableone my=new MyRunnableone();
MyRunnableone my1 =new MyRunnableone();
my.start();
my1.start();
}
}
2. Create a thread by implementing the Runnable interface
Same as the first one, create the implementation class first:
package oneTwo;
public class MyRunnabletwo implements Runnable{
public void run() {
for(int i=1;i<=20;i++){
System.out.println(i+".Hello, from thread"+Thread.currentThread().getName());
}
}
}
Remain method:
package oneTwo;
public class testtwo {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyRunnabletwo my=new MyRunnabletwo();
MyRunnabletwo my1=new MyRunnabletwo();
Thread tr=new Thread(my);
Thread tr1=new Thread(my1);
tr.start();
tr1.start();
}
}
3. Use multi-threading to simulate multi-person hiking
First create an inheritance or implementation class (I used inheritance here):
package oneThree;
public class MyRunnablethree extends Thread{
private int time;
public int num=0;
public MyRunnablethree(String name,int time,int kio) {
super(name);
this.time=time;
this.num=kio*1000/100;
}
public void run() {
while (num>0) {
try {
Thread.sleep(this.time);
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace ();
}
System.out.println(Thread.currentThread().getName()+"Climbed 100 meters! ");
num--;
}
System.out.println(Thread.currentThread().getName()+"End point reached!");
}
}
Remain method:
package oneThree;
public class testthree {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyRunnablethree young=new MyRunnablethree("Young man", 500, 1);
MyRunnablethree old=new MyRunnablethree( "Elderly", 1500, 1);
MyRunnablethree child=new MyRunnablethree("Child", 600, 1);
System.out.println("************Start climbing the mountain *********");
old.start();
young.start();
child.start();
}
}
4. Display and set thread priority
Inherit or implement the class first:
package oneFour;
public class MyRunnablefour extends Thread{
public void run() {
Thread.currentThread().setPriority(1);
System.out.println("Sub-thread name: "+Thread.currentThread().getName()+", priority : "+Thread.currentThread().getPriority());
}
}
Then main:
package oneFour;
public class testfour {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
MyRunnablefour myf=new MyRunnablefour();
myf.start();
System.out.println("****************Display the default priority********");
System.out .println("Main thread name: "+Thread.currentThread().getName()+", priority: "+Thread.currentThread().getPriority());
Thread.currentThread().setPriority(10 );
System.out.println("********************************** after modifying the default priority");
//myf.setPriority (1);
System.out.println("Main thread name: "+Thread.currentThread().getName()+", priority: "+Thread.currentThread().getPriority());
//System.out.println("Sub-thread name: "+MyRunnablefour.currentThread().getName()+", priority: "+MyRunnablefour.currentThread().getPriority());
}
}
5. Simulate calling a number and seeing a doctor
First inherit or implement the class:
package oneFive;
public class MyRunnablefive extends Thread{
private int time;
//public int pertail=0;
public MyRunnablefive(String common,int time) {
super(common);
this. time=time;
}
public void run() {
Thread.currentThread().setPriority(8);
for(int i=1;i<=10;i++ ){
try {
Thread.sleep(this.time);
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}
System.out.println("Special number: "+i+" patient is seeing a doctor! ");
}
}
}
Remain:
package oneFive;
public class testfive {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
//MyRunnablefive pertail=new MyRunnablefive(" Special number", 1000);
Thread temp=new Thread(new MyRunnablefive("Special number", 400));
temp.start();
Thread.currentThread().setPriority (4);
for(int i=1;i<=50;i++){
if(i==11){
try {
temp.join ();
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}
}
try {
Thread.sleep (200);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("Normal number :"+i+"patient is being treated");
}
}
}
6. Multi-threaded simulation relay race
First Create an inheritance or implementation class:
package oneSix;
public class runSix implements Runnable{
private int meters=1000;
public runSix(){
}
@Override
public void run() {
// TODO Auto-generated method stub
//System.out.println("Coming in");
while (true) {
//type type = (type) true.nextElement();
synchronized (this) {
if(meters<=100){
break;
}
System.out.println(Thread.currentThread().getName()+" Got the baton! ");
for (int i = 0; i < 100; i+=10) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"ran"+(i+10 )+"meters!");
}
meters-=100;
}
}
}
}
Then main interface class:
package oneSix;
public class testsix {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
runSix ru=new runSix();
for (int i = 0; i < 5; i++) {
new Thread(ru,(i+1) +"Player No.").start();
}
}
}
7. Multi-threaded simulated network ticket purchase
Taopaopao, Zhang votes, scalpers, grab ten votes together, limit scalpers to only grab one ticket
First create an inheritance or implementation class:
package oneSeven;
public class siteSeven implements Runnable{
private int count=10;
private int num=0;
private boolean flag=false;
@Override
public void run () {
// TODO Auto-generated method stub
//System.out.println("Coming in");
while (!flag) {
synchronized (this) {
//System.out.println("Coming in");
if(count<=0){
flag=true;
return;
}
num++;
count--;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace( );
}
String name=Thread.currentThread().getName();
if(name.equals("scalper")){
System.out.println(name+"rob The "+num+"th ticket is reached, and "+count+" tickets remain! ");
break;
}
System.out.println(name+"Grab the "+num+"th ticket, "+count+" tickets remaining! ");
}
}
}
}
Create the main interface class again:
package oneSeven;
public class testseven {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto- generated method stub
siteSeven si=new siteSeven();
Thread per1=new Thread(si,"Dadong");
Thread yellow=new Thread(si,"Scalper");
Thread per2=new Thread(si,"Qizhen");
per1.start();
yellow.start();
per2.start();
}
}
Four: Summary:
1. The methods in the Thread class implement operations on thread objects
①Adjust the priority of the thread
② Thread sleep sleep()
③ Thread forced operation join()
④Thread courtesy yield()
2. Multi-threading allows programmers to write programs that maximize the use of the CPU Efficient program
3. Two ways to create a thread:
①Declare a subclass that inherits the Thread class and implement the run() method of the Thread class
②Declaration A class that implements the Runnable interface, and then implements the run() method
The above is the detailed content of Introduction to the understanding and use of multi-threading. For more information, please follow other related articles on the PHP Chinese website!