1, multithreading (Introduction of multithreading)
- 1. What is a thread
- A thread is a path that a program executes, and a process can contain multiple threads
- Multi-threaded concurrent execution can improve the efficiency of the program and can do multiple tasks at the same time
- 2. Multi-Threaded application scenarios
- Red spider sharing screen to multiple computers at the same time
- Thunderbolt open multiple threads to download together
- QQ at the same time and many people together video
- The server processes multiple client requests at the same time
2. Multithreading (the difference between multithreading parallelism and concurrency)
- Parallel is two tasks at the same time, that is, a task is carried out at the same time, B task is also in progress. (Multi-core CPU required)
- Concurrency means that two tasks are requested to run, and the processor can only be subject to a single task, the two tasks are scheduled to take turns, because the time interval is short, making people feel that both tasks are running.
- For example, I chat with two netizens, left hand operation a computer with a chat, while the right hand with another computer with B chat, this is called parallel.
- If you use a computer I send a message first, and then immediately give a message to B, and then chat with a, and then chat with B. This is called concurrency.
3, multi-threaded (Java program running principle and JVM startup is multi-threaded?)
4. Multithreading (How to implement multithreaded programs 1)
1. Inherit thread
- Define class inheritance Thread
- Overriding the Run method
- Write what the new thread is going to do in the Run method
- To create a thread object
- Opens a new thread, and the Run method is automatically executed internally
public class Demo2_Thread { /** * @param args */ public static void main(String[] args) { MyThread mt = new MyThread(); //4,创建自定义类的对象 mt.start(); //5,开启线程 for(int i = 0; i < 3000; i++) { System.out.println("bb"); } }}class MyThread extends Thread { //1,定义类继承Thread public void run() { //2,重写run方法 for(int i = 0; i < 3000; i++) { //3,将要执行的代码,写在run方法中 System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaa"); } }}
5. Multithreading (How to implement multithreaded programs 2)
2. Implement Runnable
- Defining a class implementation runnable interface
- Implementing the Run Method
- Write what the new thread is going to do in the Run method
- Creating a child class object for a custom runnable
- Create thread object, incoming runnable
Call Start () to open a new thread, the internal automatically calls the Runnable run () method
public class Demo3_Runnable { /** * @param args */ public static void main(String[] args) { MyRunnable mr = new MyRunnable(); //4,创建自定义类对象 //Runnable target = new MyRunnable(); Thread t = new Thread(mr); //5,将其当作参数传递给Thread的构造函数 t.start(); //6,开启线程 for(int i = 0; i < 3000; i++) { System.out.println("bb"); } }}class MyRunnable implements Runnable { //1,自定义类实现Runnable接口 @Override public void run() { //2,重写run方法 for(int i = 0; i < 3000; i++) { //3,将要执行的代码,写在run方法中 System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaa"); } }}
6, multi-thread (realize runnable principle)
- View Source
- 1, look at the constructor of the thread class, passing a reference to the Runnable interface
- 2, use the init () method to find the target assignment of the passed target to the member variable
- 3, look at the Run method and find out in the Run method that the Run method of the Runnable interface subclass object is called if Target is not null
7, Multi-threaded (two different ways)
8, Multi-threaded (anonymous inner class two ways to implement threading)
Inherit the thread class
new Thread() { //1,new 类(){}继承这个类 public void run() { //2,重写run方法 for(int i = 0; i < 3000; i++) { //3,将要执行的代码,写在run方法中 System.out.println("aaaaaaaaaaaaaaaaaaaaaaaaaaaa"); } }}.start();
Implementing the Runnable Interface
new Thread(new Runnable(){ //1,new 接口(){}实现这个接口 public void run() { //2,重写run方法 for(int i = 0; i < 3000; i++) { //3,将要执行的代码,写在run方法中 System.out.println("bb"); }
9. Multithreading (get first name and set name)
- 1. Get the name
- Gets the name of the thread object through the GetName () method
-
2. Set name
- Pass constructor to pass in string type name
-
new Thread ("xxx") {public void run () { for (int i = 0; i < i++) {System.out.println (This.getname () + ".... aaaaaaaaaaaaaaaaaaaaaaa"); }}}.start (); New Thread ("yyy") {public void run () {for (int i = 0; i <; i++) {SYSTEM.O Ut.println (This.getname () + ".... bb"); }}}.start ();
- to set the name of a thread object by using the SetName (String) method
-
Thread t1 = new Thread () {public void Ru N () {for (int i = 0; i < i++) {System.out.println (This.getname () + ".... aaaaaaaaaaaaaaaaaaaaaa A "); } }}; Thread t2 = new Thread () {public void run () {for (int i = 0; i <; i++) {System.out.println ( This.getname () + ".... bb");
}}};t1.setname ("Sister Furong"); T2.setname ("Sister Feng"); T1.start (); T2.start ();
10, multithreading (Gets the object of the current thread)
11. Multithreading (dormant threads)
Thread.Sleep (milliseconds, nanoseconds), controls the current thread sleeps for several milliseconds 1 seconds = 1000 milliseconds 1 seconds = 1000 * 1000 * 1000 nanoseconds 1000000000
new Thread() { public void run() { for(int i = 0; i < 10; i++) { System.out.println(getName() + "...aaaaaaaaaaaaaaaaaaaaaa"); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); new Thread() { public void run() { for(int i = 0; i < 10; i++) { System.out.println(getName() + "...bb"); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start();
12. Multithreading (daemon thread)
Setdaemon (), sets a thread as the daemon thread, which is not executed separately, and exits automatically when other non-daemon threads have finished executing
13. Multithreading (join thread)
14. Multithreading (comity thread)
15, multi-threaded (set the priority of the thread)
- SetPriority () Sets the priority of the thread
16. Multithreading (Synchronous code block)
17. Multithreading (synchronous method)
Use the Synchronized keyword to decorate a method in which all the code in the method is synchronized
class Printer { public static void print1() { synchronized(Printer.class){ //锁对象可以是任意对象,但是被锁的代码需要保证是同一把锁,不能用匿名对象 System.out.print("黑"); System.out.print("马"); System.out.print("程"); System.out.print("序"); System.out.print("员"); System.out.print("\r\n"); } } /* * 非静态同步函数的锁是:this * 静态的同步函数的锁是:字节码对象 */ public static synchronized void print2() { System.out.print("传"); System.out.print("智"); System.out.print("播"); System.out.print("客"); System.out.print("\r\n"); }}
18. Multithreading (thread safety issues)
- Thread safety issues can occur when multiple threads concurrently manipulate the same data
The use of synchronization technology can solve this problem, the operation of the code to synchronize the data, not to work with multiple threads
public class Demo2_synchronized {/** * @param args * Demand: railway ticket sales, altogether 100, through four windows sold out. */public static void main (string[] args) {Ticketsseller T1 = new Ticketsseller (); Ticketsseller t2 = new Ticketsseller (); ticketsseller t3 = new Ticketsseller (); ticketsseller T4 = new Ticketsseller (); T1.setname ("Window 1"); T2.setname ("Window 2"); T3.setname ("Window 3"); T4.setname ("Window 4"); T1.start (); T2.start (); T3.start (); T4.start (); }} class Ticketsseller extends Thread {private static int tickets = 100; Static Object obj = new Object (); Public Ticketsseller () {super (); } public Ticketsseller (String name) {super (name); The public void, run () {while (true) {synchronized (obj) {if (tickets < ; = 0) Break try {thread.sleep (10);//thread 1 sleeps, thread 2 sleeps, thread 3 sleeps, thread 4 sleeps} catch (Interruptedexception e) { E.printstacktrace (); } System.out.println (GetName () + "... This is the first "+ tickets--+" ticket "); } } } }
19, multi-threaded (railway station ticket sales example with the implementation of the Runnable interface)20. Multi-threaded (deadlock)
21. Multithreading (Previous thread-safe Class review)
- A: Review the thread safety issues previously mentioned
- See Source: vector,stringbuffer,hashtable,collections.synchroinzed (XXX)
- Vectors are thread-safe and ArrayList are thread insecure
- StringBuffer is thread-safe, StringBuilder is thread insecure
- Hashtable is thread-safe, HashMap is thread insecure
Java EE Basics (24)/multithreading