When learning the operating system , We learn about processes and threads , So what are processes and threads ?

process It is a program with certain independent functions about a running activity on a data set , A process is an independent unit of the system for resource allocation and scheduling .

Threads thread) yes operating system Be able to operate Dispatch Minimum unit of .

It is contained in process In , yes process The actual operating unit in .

A thread means process A single sequential control flow in , Multiple threads can be concurrent in one process , Each thread performs different tasks in parallel .

Java How the program works

java Command will start java virtual machine , start-up JVM, It's like starting an application , That is to start a process . The process will automatically start a “ The main thread ” , Then the main thread calls the main Method .

therefore main Method runs in the main thread . All previous programs were single threaded .

JVM Is it multithreaded ?
1、Java Command to start JVM,JVM Will start a process , The process starts a main thread .
2、JVM Is multithreaded , Because it has at least two threads to start , Main thread and garbage collection thread .

Multithreading solution
1、 Inherit Thread class

/**
* This class will override run() Method , Why? ?
* Not all code in a class needs to be executed by a thread .
* And this time , To distinguish which code can be executed by threads ,java Provides Thread Class run() Used to contain code that is executed by threads .
*
* @author sun
*
*/ public class MyThread extends Thread {
private int i; public MyThread(int i) {
super();
this.i = i;
} @Override
public void run() {
System.out.println("i=" + i);
}
}
/**
* Multithreaded testing
*
* @author sun
*
*/
public class ThreadTest {
public static void main(String[] args) {
MyThread myThread1 = new MyThread(1);
MyThread myThread2 = new MyThread(2);
MyThread myThread3 = new MyThread(3);
MyThread myThread4 = new MyThread(4);
MyThread myThread5 = new MyThread(5);
myThread1.start();
myThread2.start();
myThread3.start();
myThread4.start();
myThread5.start();
// because run() Method direct call is equivalent to ordinary method call , So what you see is a single thread effect
myThread1.run();
} }

From the code above , We can also see that , The code in the thread can also be used run Method call .

that run() and start() What's the difference between ?
run(): Just encapsulate the code executed by the thread , A direct call is a normal method
start(): First started the thread , And then by jvm To call the run() Method .

2、 Realization Runnable Interface

public class MyRunnable implements Runnable {
@Override
public void run() {
System.out.println(" Running !");
} }

/**
*
* @author sun
*
*/
public class Run {
public static void main(String[] args) {
Runnable runnable = new MyRunnable();
Thread thread = new Thread(runnable);
thread.start();
}
}

Implementation interface Runnable The benefits of this approach

Can be avoided by Java Limitations of single inheritance .

It is suitable for code of the same program to handle the same resource , Put the thread with the program code , Data is effectively separated , Better reflects the object-oriented design ideas .

  Threads have two scheduling models :

Time sharing scheduling model    All threads rotate CPU Right to use , Average per thread CPU Time slice of

Preemptive scheduling model    Give priority to high priority threads CPU, If the threads have the same priority , Then we will randomly choose one , High priority threads get CPU There are more time slices .

Java Using preemptive scheduling model .

So we already know the thread scheduling , Next, we can use the following methods to control the object thread

Thread to sleep       public static void sleep(long millis): Sleep the currently executing thread for a specified number of milliseconds ( Suspend execution

Thread join public final void join(): Wait for the thread to terminate .

Thread comity  public static void yield():  Pause the currently executing thread object , And execute other threads .

Interrupt threads  public final void stop(): Deprecated .  This method has inherent insecurity .

public void interrupt(): Interrupt threads .

/**
* Thread to sleep
*
* @author sun
*
*/
public class ThreadSleepDemo {
public static void main(String[] args) {
ThreadSleep ts1 = new ThreadSleep();
ThreadSleep ts2 = new ThreadSleep();
ThreadSleep ts3 = new ThreadSleep(); ts1.setName("sun");
ts2.setName("tin");
ts3.setName("ting"); ts1.start();
ts2.start();
ts3.start();
}
} class ThreadSleep extends Thread {
@Override
public void run() {
for (int x = 0; x < 100; x++) {
System.out.println(getName() + ":" + x + ", date :" + new Date());
// sleep , Set up 1 Second
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

public class ThreadJoinDemo {
public static void main(String[] args) {
ThreadJoin tj1 = new ThreadJoin();
ThreadJoin tj2 = new ThreadJoin();
ThreadJoin tj3 = new ThreadJoin(); tj1.setName("1");
tj2.setName("2");
tj3.setName("3"); tj1.start();
try {
tj1.join();
} catch (InterruptedException e) {
e.printStackTrace();
} tj2.start();
tj3.start();
}
} class ThreadJoin extends Thread {
@Override
public void run() {
for (int x = 0; x < 100; x++) {
System.out.println(getName() + ":" + x);
}
}
}

/**
* Pause the currently executing thread object , And execute other threads .
* @author sun
*
*/
public class ThreadYieldDemo {
public static void main(String[] args) {
ThreadYield ty1 = new ThreadYield();
ThreadYield ty2 = new ThreadYield(); ty1.setName(" Brigitte Lin ");
ty2.setName(" Liu Yi "); ty1.start();
ty2.start();
}
} class ThreadYield extends Thread {
@Override
public void run() {
for (int x = 0; x < 100; x++) {
System.out.println(getName() + ":" + x);
Thread.yield();
}
}
}
/*
* public final void stop(): Let thread stop , More violent . It is not recommended to use .
* public void interrupt(): Interrupt threads . Terminate the state of the thread , And throw a InterruptedException.
*/
public class ThreadStopDemo {
public static void main(String[] args) {
ThreadStop ts = new ThreadStop();
ts.start(); try {
Thread.sleep(3000);
// ts.stop();
ts.interrupt();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} class ThreadStop extends Thread {
@Override
public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) { } }
}

Let's talk about it first ~

java Basics 07 More articles on Multithreading

  1. Java Basic multithreading ( Thread creation and termination 、 Mutually exclusive 、 signal communication 、 The local variable )

    Thread creation and termination Thread creation Thread Class and Runnable Interface relationship public interface Runnable { public abstract void run(); } public ...

  2. About java Basics 、 Multithreading 、JavaWeb Basics 、 database 、SSM、Springboot Technical summary

    author : Stanley Luo Hao I summarize myself , Pure hand beating , If you have any questions, please leave a message in the comment area [ Please indicate the source and signature of the reprint , thank you !] One .java Basics 1. What are the forms of polymorphism ? rewrite . heavy load 2. Overriding What is the ...

  3. Java Basic multithreading framework

    One . The difference between a process and a thread 1. Definition : A process is a program with some independent functions. It is a running activity on a data set , A process is an independent unit of the system for resource allocation and scheduling . A thread is an entity of a process , yes CPU Basic unit of dispatch and dispatch , It's more than ...

  4. Java Basic multithreading detailed analysis

    Before we learn about multithreading , Let's take a look at the relationship between processes and threads . Processes and threads : A process is a program that is executing in the system , Each process is independent . A thread is a basic unit of execution of a process . A process wants to perform tasks , There must be threads ( Every time 1 individual ...

  5. java Basic knowledge of Multithreading

    package org.base.practise9; import org.junit.Test; import java.awt.event.WindowAdapter; import java. ...

  6. Java Basic knowledge of * Multithreaded programming ( 5、 ... and )

    summary Java Built in support for multithreaded programming . A multithreaded program contains two or more parts that can run concurrently . Every part of a program is called a thread , And each thread defines an independent execution path . Multithreading is also used to make full use of server resources , ...

  7. Java Basic multithreading

    1. Processes and threads : process : The program in progress . Every process execution has an execution sequence , This sequence is an execution path , Or a control unit . Threads : An execution path or a control unit within a process . The difference between the two : A process has at least one thread ...

  8. Black horse programmer ——【Java Basics 】—— Multithreading

    ---------- android train .java train . Looking forward to communicating with you ! ---------- One . summary ( One ) process Program in progress , Every process execution has an execution sequence . This sequence is an execution path , Or a controller ...

  9. Black horse programmer ——JAVA The foundation of multithreading communication between threads, etc

    ------- android train .java train . Looking forward to communicating with you ! ---------- Communication between threads : In fact, multiple threads are operating on the same resource , But the action is different . wait(); This object is called in another thread notif ...

Random recommendation

  1. git gitignore File invalidation processing

    This is about using git ignore It's a special situation at that time   Normally, after you add some files to the project locally , Generally, it will track all automatically , But at this point you have to edit one ignore file , Put something that doesn't need to be traced to a file ignor ...

  2. jQuery Future generations / Reverse election checkbox

    <!doctype html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  3. visual studio Compile time appear Files Value The statement

    Refer to the :http://blog.163.com/jiang_tao_2010/blog/static/121126890201031031337332/ When I was working on the program recently , In the process of generating solutions , The computer appears ...

  4. poj2387 Til the Cows Come Home

    Their thinking : The shortest path template question , Just pay attention to one detail . See the code : #include<cstdio> #include<cstring> #include<algorithm&g ...

  5. oracle rac scan ip purpose principle

    Oracle 11G R2 RAC Added scan ip function , stay 11.2 Before ,client Link to the database with vip, If your cluster Yes 4 Nodes , So the client's tnsnames.ora There are four of them ...

  6. 《python Basic course 》 Note it Dictionaries

    Dictionary creation A dictionary consists of multiple key value pairs , Each key is separated from the corresponding value by a colon , Separate items with commas , And the whole dictionary is enclosed in a pair of braces , Such as >>> phonebook={'alice':'0123', 'Be ...

  7. Nine sorting algorithms Demo

    1. Bubble sort Bubble sort (Bubble Sort) It's a simple sort algorithm . It repeatedly visits the sequence to be sorted , Compare two elements at a time , If they're in the wrong order, exchange them . The job of the interview sequence is to repeat until there is no need to exchange , ...

  8. nginx+tomcat Installation configuration

    nginx+tomcat Installation configuration # nginx+tomcat Installation configuration # Create site directory mkdir -p /www/wwwroot cd /www # Installation configuration wget http://mirrors. ...

  9. c++ --&gt; cin and cout I / O format

    cin and cout I / O format Cout Output 1>. bool Type output cout << true <<" or " << false < ...

  10. ITextSharp structure PDF file

    1.1  Generate Document Document It's what we're going to generate PDF A container for all elements of a file , So to generate a PDF file , You have to first define a Document object . Document There are three types of constructors :    publ ...