Java Learning notes Multi-threading

Source: Internet
Author: User

/* Process: A program that is in progress (literal translation). Thread: A control unit (execution path) in the process that is responsible for program execution. There can be multiple execution paths in a process. Called Multithreading. You must have at least one thread in a process. Multiple threads are turned on to run multipart code at the same time. Each thread has its own running content. This content can be referred to as the task that the thread is performing. Multithreading Benefits: Solves the problem of multi-part simultaneous running. Disadvantages of Multithreading: Too many threads return to reduced efficiency. In fact, the implementation of the application is the CPU is doing a fast switchover done. This switch is random. The JVM starts with multiple threads, at least two threads can be parsed. 1. The thread that executes the main function's task code is defined in the main function in 2. The thread responsible for the garbage collection. */class Demo extends Object{public void Finalize ()//used to reclaim {System.out.println ("Demo OK");}} Class Threaddemo{public static void Main (string[] args) {new demo (); new demo (); new demo (); System.GC (); System.out.println ("Hello world!");}} /********************************************///How multi-threading is created-inherit the thread class/* Step: 1. Defines a class that inherits the thread Class 2. Override the Run method 3 in the thread class. Create thread 4 by creating the subclass object of thread directly. Call the Start method to open the thread and invoke the thread's task to execute the Run method. You can get the name of the thread through the thread's GetName thread-number (starting from 0) The first name is Main.*/class Demo extends thread{ private string Name;demo (string name) {super (name);//custom thread name this.name = name;} public void Run () {Show ();} public void Show () {//system.out.println (name+ "... x=" +x+ "... name=" +getname ());; System.out.println (name+ "..... x=" +x+ ".....Name= "+thread.currentthread (). GetName ());//The name of the currently running thread.}} Class Threaddemo2{public static void Main (string[] args) {/* creates the thread's parent in order to open an execution path, To run the specified code and other code to run at the same time. The specified code that runs is the task for this execution path. The tasks for the main thread created by the JVM are defined in the main function. and the custom thread where is its task? The thread class is used to describe threads, which require tasks, so the thread class also describes the task. This task is represented by the Run method in the thread class. That is, the Run method is the function that encapsulates the custom thread that runs the task. The Run method is defined as the task code that the thread will run. The thread is turned on to run the specified code, so only the thread class is inherited and the Run method is replicated. Define the running code in the Run method. */demo D1 = new Demo ("Mong Choi");D emo d2 = new Demo ("Xiaoqiang");//d1.run ();//d2.run ();d 1.start (); Open thread, call the Run Method D2.start (); System.out.println ("Over ..." +thread.currentthread (). GetName ());}} /*******************************************************************************///the second way to create multithreading--Implement Runnable interface/* 1. Define the class implementation runnable interface 2. Overwrite the Run method in the interface, encapsulating the thread's task code into the Run method. 3. The thread object is created through the thread class and the subclass object of the Runnable interface is passed as a parameter to the constructor of the thread class. Why? Because thread tasks are encapsulated in the Run method of the Runnable interface subclass object, you must explicitly define the task to run when the thread object is created. 4. Call the Start method of the threading object to open the thread. */class Demo implements runnable{ public void Run ()//runnable has only one run method {show ();} public void Show () {for (int x=0; x<20;X + +) {System.out.println (Thread.CurrentThread (). GetName () + "..." +x);}} Class Treaddemo{public static void Main (string[] args) {Demo d = new demo (); thread T1 = new Thread (d); Pass d in to thread t2 = new Thread (d); T1.start (); T2.start ();}} /* Benefits of implementing the Runnable interface: 1. The task of the thread is separated from the subclass of the thread and is individually encapsulated. Encapsulates a task into an object based on object-oriented thinking. 2. Avoids the limitations of Java single inheritance. Therefore, the second way to create a thread is more common. *//********************************************************************//* Example: Sell tickets. Four people sell 100 tickets together *///the first method class Ticket extends thread{private static int num = 100;//This variable to be shared, so add static public void run () {sale () ;} public void Sale () {while (true) {if (num>0) {System.out.println (num--);}}} Class Ticketdemo{public static void Main (string[] args) {Ticket T1 = new Ticket (); Ticket t2 = new Ticket (); Ticket t3 = new Ticket (); Ticket T4 = new Ticket (); T1.start (); T2.start (); T3.start (); T4.start ();}} The second method class Ticket implements runnable{private int num = 100;public void run () {sale ();} public void Sale () {while (true) {if (num>0) {try{thread.sleep (10);} catch (Interruptedexception e) {}system.out.println (Thread.CurrentThread (). GetName () + "..." +num--);}}}   Class Ticketdemo{public static void Main (string[] args) {Ticket t = new Ticket (); Because only one object is created, the following 4 processes are opened, so it is equal to 4 people selling together to sell 100 tickets thread t1 = new Thread (t); Thread t2 = new Thread (t); thread t3 = new Thread (t); thread T4 = new thread (t); T1.start (); T2.start (); T3.start (); T4.start ();}} /* Causes of thread safety problems: 1. Multiple threads are working on shared data. 2. The thread code that operates the shared data has multiple threads. When a thread executes multiple code processes that share data, other threads take part in the operation, which can lead to thread safety problems. The solution is to encapsulate the thread code that shares the data with multiple operations. When the thread is executing the code, the other threads are not allowed to participate in the operation. It is necessary for the thread to be able to participate in the operation after the code has been executed. In Java, synchronizing blocks of code can solve this problem. *//************************ Synchronizing code blocks/* Format: Synchronized (object) {code}*/class required to be synchronized Ticket Implements runnable{private int num = 100;object obj = new Object ();p ublic void Run () {sale ();}  public void Sale () {//object obj = new Object (); It is wrong in this way, so that each thread that is opened creates a lock that is 4 threads together with 4 locks while (true) {synchronized (obj)///synchronous code block {if (num>0) {try{thread.sleep (10);} catch (Interruptedexception e) {}system.out.println (threAd.currentthread (). GetName () + "..." +num--);}}} Class Ticketdemo{public static void Main (string[] args) {Ticket t = new Ticket (); thread T1 = new Thread (t); Thread t2 = new Thread (t); thread t3 = new Thread (t); thread T4 = new thread (t); T1.start (); T2.start (); T3.start (); T4.start ();}} /* Benefits of synchronization: Resolves thread security issues. The disadvantage of synchronization: the relative reduction of efficiency, because the synchronization of the thread will judge the synchronization lock. Prerequisites for synchronization: You must have multiple threads and use the same lock. *//************************************* * Example: Depositors, two, each to the bank to save money, each time to save 100, coexistence three times. */class bank{private int Sum;//private Object obj = new Object ();p ublic synchronized void add (int num)///can also be used with the synchronization function {//synchronized (obj)//{sum = sum + num; System.out.println ("sum=" +sum);//}}}class Cus implements runnable{private Bank B = new Bank ();p ublic void Run () {for (int x = 0; x<3; X + +) {b.add (100);}}} Class Bankdemo{public static void Main (string[] args) {Cus c = new Cus (); thread T1 = new Thread (c); Thread t2 = new Thread (c); T1.start (); T2.start ();}} /*********************************************************///Verify the Lock class Ticke of the sync functionT implements runnable{private int num = 100;object obj = new Object (); Boolean flag = True;public void Run () {//object obj =  New Object (); It is wrong in this way, so that each thread that is opened creates a lock that is 4 threads together with 4 locks if (flag) {while (true) {synchronized (this)//synchronous code block {if (num>0) {try{ Thread.Sleep (10);} catch (Interruptedexception e) {}system.out.println (Thread.CurrentThread (). GetName () + "... obj ..." +num--);}}} else while (true) show ();} Public synchronized void Show ()//But this can be used to encapsulate the code that needs to be synchronized. {if (num>0) {try{thread.sleep (10);} catch (Interruptedexception e) {}system.out.println (Thread.CurrentThread (). GetName () + [...] function ... "+num--);}} Class Synfunctionlockdemo{public static void Main (string[] args) {Ticket t = new Ticket (); thread T1 = new Thread (t); Thread t2 = new Thread (t); T1.start (); Try{thread.sleep (10);} catch (Interruptedexception e) {}t.flag = False;t2.start ();}} /* The lock used by the sync function is this. The difference between a synchronization function and a synchronous code block: The lock of the synchronization function is fixed. The lock of the synchronization code block is arbitrary. It is recommended to use a synchronous code block. */


Java Learning notes Multi-threading

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.