Java basic notes-multithreading and java notes Multithreading

Source: Internet
Author: User

Java basic notes-multithreading and java notes Multithreading

Thread:

Method 1: Inherit the Thread class and re-write the run method.

Format:

Class MyThread extends Thread

{

Public void run ()

{

The code to run in the thread.

}

}

The procedure is as follows:

1. The definition class inherits the Thread class.

2. Review the run method. ----> the purpose is to store the code to be run in the thread, store the custom code in the run method, and let the thread run.

3. Call the start method of the thread.

Note: The run method is not called.

 

Thread name: Generally, the Thread has a default name in the form of Thread-number, which is marked from 0.

You can also obtain the name of the currently running Thread by Using Thread. currentThread (). getName ()

Thread. currentThread () is used to obtain the object of the current Thread. (Static ).

You can use setName () or constructor to set the thread name.

 

Code examples and exercises on thread inheritance:

1/* 2 threads: Step 3 1. define a class to inherit from Thread 4 2. method 5 in the rewrite class. create an object (a thread is created when an object is created) 6. call the start () method of the thread. After the start method is called, the thread is started and the run () method is also called. 7 */8 class MyThread extends Thread // Step 9 {10 public void run () // Step 11 {12 for (int x = 0; x <60; x ++) 13 System. out. println ("MyThread run! ==== "+ X); 14} 15} 16 17 18 class ThreadDemo19 {20 public static void main (String args []) 21 {22 MyThread mt = new MyThread (); // a thread is created. // step 3 23 mt. start (); // start the thread and run the run method of the thread. // Step 4 24 // mt. run (); // It is only an object call method. Although a thread is created, the thread is not run. 25 26 for (int x = 0; x <60; x ++) 27 System. out. println ("Hello World! ==== "+ X); 28} 29}View Code 1/* 2 3 */4 class FirstThread extends Thread 5 {6 // private String name; 7 FirstThread (String name) 8 {9 // this. name = name; 10 super (name); 11} 12 public void run () 13 {14 for (int I = 1; I <= 50; I ++) 15 {16 // System. out. println (this. name + "FirstThread run. ===== "+ I); 17 System. out. println (Thread. currentThread () = this) + "...... "+ this. getName () + "FirstThread run. ==== "+ I); 18} 19} 20} 21 22 class ThreadTest23 {24 public static void main (String args []) 25 {26 FirstThread ft1 = new FirstThread ("First ="); 27 FirstThread ft2 = new FirstThread ("Second ="); 28 ft1.start (); 29 ft2.start (); 30 31 for (int I = 1; I <= 50; I ++) 32 {33 System. out. println ("mainThread run. ==== "+ I); 34} 35} 36}View Code
1/* 2 ticket window example: 3 multiple windows can sell tickets at the same time. 4 */5 6 class Ticket extends Thread 7 {8 private static int ticket = 100; // when static is not required. both Windows will sell tickets with the same number, that is, 100 tickets will be sold once (equivalent to 200 times) 9 Ticket (String name) 10 {11 super (name ); 12} 13 public void run () 14 {15 while (true) 16 {17 if (ticket> 0) 18 {19 System. out. println (Thread. currentThread (). getName () + "=== selling tickets ===" + ticket --); 20} 21} 22} 23} 24 25 26 class TicketDemo27 {28 public static void main (String args []) 29 {30 Ticket t1 = new Ticket ("Window 1 "); 31 Ticket t2 = new Ticket ("window 2"); 32 t1.start (); 33 t2.start (); 34 35} 36}

 


The second thread method:

Implement the Runnable interface:

Format:

Class MyRunnable implements Runnable

{

Public void run ()

{

The code to run in the thread.

}

}

The steps are generally:

1. Define a class to implement the Runnable interface.

2. Rewrite the run method in the Runnable interface.

3. Create an object using the Thread class.

4. Pass the object of the Runnable subclass to the constructor In the Thread class as an actual parameter.

5. Call the start method in the Thread class. Enable the Thread and call the run method of the subclass of the Runnable interface. (it can be understood as the run method and start method to enable the call)

For example:

Class MyRunnable implements Runnable // Step 1

{

Public void run () // Step 2

{

S. o. p ();

}

}

Class RunnableDemo

{

P.s. v. main ()

{

MyRunnable mr = new MyRunnable ();

Thread t1 = new Thread (mr); // Step 3-4

T1.start (); // Step 5

}

}

1/* 2 ticket window example: 3 multiple windows can sell tickets at the same time. 4. Do not use static ticket to sell tickets in each window, And do not sell repeated tickets. 5. Implement the Runnable interface. 6 7. method 2 for thread creation: 8. Implement the Runnable interface. 9 steps: 10 1. define a class implementation (implements) Runnable interface 11 2. rewrite the run Method 12 in the Runnable interface. 3. use the Thread class to create object 13 4. pass the subclass object of the Runnable interface as the actual parameter to the constructor In the Thread class. 14 5. call the start method in the Thread class to enable the Thread and call the run method of the subclass of the Runnable interface. 15 */16 17 18 class Ticket implements Runnable19 {20 private int ticket = 100; // private static int tick Et = 100; 21/* 22 because Ticket does not inherit the Thread, this class does not have the getName () method, so it cannot be called. 23 Ticket (String name) 24 {25 super (name); 26} 27 */28 public void run () 29 {30 while (true) 31 {32 if (ticket> 0) 33 {34 System. out. println (Thread. currentThread (). getName () + "= selling tickets ====" + ticket --); 35} 36} 37} 38} 39 40 41 class RunnableTicketDemo42 {43 public static void main (String args []) 44 {45 Ticket t = new Ticket (); // t is shared data. 46 47/* 48 When the preceding method is not static, ticket will sell 200 tickets. How can I disable static ticket = 100 and customize the thread name without selling 200 tickets ???? 49 */50 // Ticket tt = new Ticket (); 51 // Ticket ttt = new Ticket (); 52 // Ticket tttt = new Ticket (); 53 54 // Thread t1 = new Thread (t, "Window 1"); 55 // Thread t2 = new Thread (tt, "window 2 "); 56 // Thread t3 = new Thread (ttt, "window 3"); 57 // Thread t4 = new Thread (tttt, "Window 4 "); 58/* 59 after the code below is executed, Thread. currentThread (). getName () gets the default thread name. 60 */61 Thread t1 = new Thread (t); 62 Thread t2 = new Thread (t); 63 Thread t3 = new Thread (t ); 64 Thread t4 = new Thread (t); 65 66 t1.start (); 67 t2.start (); 68 t3.start (); 69 t4.start (); 70} 71}View Code

The differences and features between the inheritance and implementation modes are as follows:

Implementation Method: avoids the limitation of single inheritance. We recommend that you use the implementation method when defining a thread.

Differences:

1. inherit Thread: the Thread code is stored in the run method of the sub-class of Thread.

2. Runnabel implementation: the code of the thread is stored in the run method of the subclass of the Runnable interface.

 

Finally, the synchronization code block solves the security problem of multithreading.

Format:

Synchronized (object)

{

Code block to be synchronized.

}

Examples and exercises for implementing the Runnable interface and synchronization:

1/* 2 multi-thread security issues; 3. The number of votes printed is 0. -1. -2. 4 5 Problem Analysis: when multiple statements use shared data of the same thread at the same time, one thread only executes a part of the data, and the other thread is involved in the execution, data sharing error. 6. In the if judgment, when ticket = 1, after one thread enters the execution statement, the other thread also executes the statements. 7 at this time, ticket has changed to 0 through ticket, resulting in the output of the number of votes is 0 or a negative number. 8. Solution: 9. For statements that operate on multiple shared data records, the execution of one thread is completed before another thread is executed, so as to avoid this problem. 10 11 synchronization code block. keyword: synchronized12 format: 13 synchronized (object) 14 {15 code to be synchronized. 16 {17 18 synchronization conditions: 19 1. it must be multi-threaded and cannot be synchronized in a single thread. 20 2. the same lock must be used by multiple threads. 21 ensure that only one thread is running in synchronization. 22 23 synchronization benefits: security issues of multithreading are solved. 24 disadvantages: Every thread must judge the lock, which affects the program running speed and consumes resources. 25 */26 class Ticket implements Runnable27 {28 private int ticket = 100; 29 Object obj = new Object (); 30 public void run () 31 {32 while (true) 33 {34 synchronized (obj) // obj is equivalent to a lock. 35 {36 if (ticket> 0) 37 {38 // try {Thread. sleep (10);} catch (Exception e) {} 39 System. out. println (Thread. currentThread (). getName () + "= selling tickets ====" + ticket --); 40} 41} 42} 43} 44} 45 46 class RunnableTicketSafeDemo47 {48 public static void main (String args []) 49 {50 Ticket t = new Ticket (); // t is shared data. 51 52 Thread t1 = new Thread (t); 53 Thread t2 = new Thread (t); 54 Thread t3 = new Thread (t ); 55 Thread t4 = new Thread (t); 56 57 t1.start (); 58 t2.start (); 59 t3.start (); 60 t4.start (); 61} 62}

 

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.