Learning multi-thread basis, this one enough friends! (One)

table of Contents

Part I: Basic Concepts

Part II: How to Create a thread

A way to create threads: Thread class inheritance.

Create a thread way: implement Runnable.

Example: with a total of 100 tickets to sell four windows (to be improved version)

Security threads: Part III

example:

The reason of thread safety problems:

Thread safety problem-solving ideas:

Multithreading singleton involved

 

Part I: Basic Concepts

To understand what is thread, first understand what the process is.

  1. Process: Simple to understand the program in progress
  2. Control unit (execution path) is a process responsible for program execution: Thread
  3. Multithreading: A process has multiple execution paths. (Multiple lane on the road)

 

Open multiple threads to simultaneously run multiple parts of the code (anti-virus while cleaning up litter).

 

Each thread has its own operational content. This content can be called a task threads to execute.

 

The benefits of multithreading: solve the problem of multi-part code that runs at the same time.

Multithreading drawbacks: too many threads efficiency. (Because the execution of the application is doing cpu fast switching completed. This switch is random.)

 

JVM startup started the multiple threads, there are at least two threads can analyze it.

1, the main function of executing thread, the thread of the task code is defined in the main function.

2, finalize responsible for garbage collection thread.

 

Part II: How to Create a thread

A way to create threads: Thread class inheritance.

step:

1, the definition of a class inheritance Thread class.

2, covering the run method of the Thread class. (Run method defined in the code is the task threads to run.)

3, directly create a subclass of Thread objects to create a thread.

4, call the start method (method not run!) Open thread and the calling thread run method of task execution.

 

Comment:

  1. All code is not in the class need to be thread. In order to be able to distinguish what a thread of execution of code, java class provides run Thread () method to those containing a thread of execution code.
  2. Call the run () and start () call difference: call run () is just an ordinary call is single-threaded, and call start () is divided into two steps, first started the thread, run the thread again called by the jvm ().
class Demo2 extends Thread    //创建线程的第一步:继承Thread类
{
	private String  name;
	Demo2(String name)
	{
		
		this.name = name;
	}
	
	
	public void run()       //创建线程的第二步: 覆盖Thread类中的run方法:写入要执行的代码
	{
		
		//需要此线程完成的功能代码
		System.out.println("名字是"+name);
	}
}

class ThreadDemo2 
{
	public static void main(String[] args) {
		

		Demo2 d1 = new Demo2("旺财");   //创建线程的第三步:创建Thread的子类对象创建线程。
		Demo2 d2 = new Demo2("xiaoqiang");
		d1.start();//创建线程的第四步:调用start方法开启线程并调用线程的任务run方法执行,虚拟机会调用该线程的run方法
		d2.start();
		 
		System.out.println("over...."+Thread.currentThread().getName()); //获取线程的名称,格式:Thread-编号(从0开始)
	}
	
}

 

 

(Supplement: currentThread (): Returns the currently executing thread object)

 

Three operating results :( multithreaded understood as different lanes, different lanes actual vehicle speed, so the operating results will be biased)

 

 

 

 

 

Create a thread way: implement Runnable.

1, defining class implements Runnable interface.

2, covering the run method interface, the task code encapsulated thread run method.

3, and the Runnable interface subclass object as a parameter Thread class constructor is passed through the Thread class objects to create threads.

       why? Because threads run tasks are encapsulated in the Runnable interface method subclass object.

       So it must be clear mandate to run when the thread object is created.

4, the calling thread object's start method open thread.

class Demo3 implements Runnable //创建线程的第一步:定义类实现Runnable接口。
{
	public void run()//创建线程的第二步:覆盖接口中的run方法,将线程的任务代码封装到run方法中。
	{
		for(int x=0; x<20; x++)
		{
			System.out.println(Thread.currentThread().getName()+"....."+x);
		}
	}
}


class  ThreadDemo3
{
	public static void main(String[] args) 
	{	
		Demo3 d = new Demo3();
		Thread t1 = new Thread(d);//创建线程的第三步:通过Thread类创建线程对象,并将Runnable接口的子类对象作为Thread类的构造函数的参数进行传递。
		Thread t2 = new Thread(d);
		t1.start();//创建线程的第四步:调用线程对象的start方法开启线程。
		t2.start();
	}
}

 

 

Implement Runnable benefits:

1, the task thread separated from the thread of the subclass, were individual packages.

       According to object-oriented thinking will be packaged as a thread task object.

2, to avoid the limitations of single inheritance java.

So, to create threads of the second approach is more commonly used.

 

 

Example: with a total of 100 tickets to sell four windows (to be improved version)

class Ticket implements Runnable
{
	private  int num = 100; 
	public void run()
	{
		while(true)
		{
			if(num>0)
				{
					System.out.println(Thread.currentThread().getName()+" is saleing 第"+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();
//		t1.start();
//		t1.start();//一个线程不能开启两次 (线程结束后也不能再次开启),会抛出无效线程状态异常 illegalThreadStateException
	}
}

 

 

Operating results (interception part, in fact, in order to sell, but sold no time to print, so print out is out of order):

 

Thread state diagram:

 

Set the thread priority:

 

 

 

Security threads: Part III

example:

In the ticketing process, non-ideal case, when a plurality of threads simultaneously enter judgment statement (assuming that num = 1, that eligible thread proceeds), as shown below. Threads need to queue waiting to be processed. After the execution thread 0, num = 0, then execute the thread 1, num = 0, (this time does not sell tickets 0) then execute threads 2 and 3 threads, it will not result in the implementation of the consequences.

 

Incorrect consequences:

 

 

The reason of thread safety problems:

1, a plurality of threads operating in the shared data.

2, operation of shared data a plurality of threaded code.

 

When a plurality of thread execution code for operating a shared data other threads involved in the operation.

It will lead to thread safety issues.

 

 

Thread safety problem-solving ideas:

A plurality of threaded code is to share data encapsulated operation, when there is a thread of execution code,

Not involved in computing when other threads. Must be after the current thread code are executed, other threads can participate in operations. (Simply means that the threads do not let the same thing at the same time, have to queue up)

 

 

In java with the synchronized block (encapsulation of multiple statements) can solve this problem.

 

Block sync code format:

synchronized (Object)

{

       Synchronization code is required;

}

 

 

Synchronization functions: synchronization code blocks may be considered short form of the function is the keyword in the synchronized synchronous function

And the difference between the synchronization code synchronization function blocks:

Lock synchronization function is fixed this, who calls who is locked

Lock synchronization code block is arbitrary objects.

 

Static lock synchronization function uses the function belongs bytecode file object

Can be obtained by getClass method, you can also use the current class name .class representation.

 

 

Examples ticket improved version:

class Ticket implements Runnable
{
	private  int num = 100; 
	Object object =new Object();
	public void run()
	{
		while(true)
		{
			synchronized(object)
			{
			if(num>0)
				{
					try{Thread.sleep(10);}catch (InterruptedException e){}  
					System.out.println(Thread.currentThread().getName()+" is saleing 第"+num--+" 张票");
				}
			}
		}
	}
}

 

 

 

The benefits of synchronization: address security issues thread.

Synchronization drawbacks: relatively lower efficiency, because the outer thread synchronization will be determined synchronization lock. Deadlock may occur

 

Synchronization premise: There must synchronize multiple threads and use the same lock.

 

 

Multithreading singleton involved

//懒汉式
class Single{
	private static Single single =null;
	
	private Single() {}
	
	public static Single getInstance() {
		if(single==null)  //加入双重判断是为了解决效率问题。   
			//具体流程为:线程们判断single是否为空,先判断完成为空的线程进同步代码块,则其他的线程无法进去,
			//先进去的执行完出来以后,后面的进程进去再进行判断,发现不为空,则不用再new
		{
			synchronized (Single.class) //加入同步为了解决多线程安全问题。
			{
				if(single==null)
					single=new Single();


			}
		}
		return single;
	}
}

Learning multi-thread basis, this one enough friends! (B): https: //blog.csdn.net/weixin_43827227/article/details/96982701

 

Multithreading Summary:

 

1, the concept of processes and threads.

       | - Process:

       | - Thread:

 

2, multithreading jvm is reflected.

       | - the main thread, the thread garbage collection, custom threads. And the position of the code they run.

 

3, when using multi-threaded, multi-threaded What good is that? Created to thread?

       | - When the need for multi-part code is executed at the same time, it can be used.

 

4, two ways to create threads. ★★★★★

       | - Inheritance Thread

              | - Step

       | - implement Runnable

              | - Step

       | - the difference between the two approaches?

 

5, 5 state of the thread.

       For the execution and implementation of the right qualifications specific features in the state.

       | - were created:

       | - run:

       | - Freeze:

       | - temporarily blocked:

       | - demise:

 

6, security threads. ★★★★★

       | - safety reasons:

       | - solving ideas:

       | - resolved reflect: synchronized

       | - synchronized premise: but with synchronization also security problems, we need to think in the premise.

       | - synchronization methods and the difference between two forms:

       | - Synchronization of the benefits and drawbacks:

       | - lazy single example.

       | - deadlock.

      

 

7, communication between threads. Wait / wakeup mechanism.

       | - concept: multiple threads of different tasks, deal with the same resources.

       | - wait wake-up mechanism. Use a locked wait notify notifyAll. ★★★★★

       | - questions producer / consumers. And more than production and consumption issues and more. while determination flag. Wake-up each other with notifyAll. ★★★★★

       | After --JDK1.5 appeared better solution, ★★★

              Lock the interface replaces the synchronized 

              Condition Object Interface alternative method of monitoring, the monitor and packaged in a method of Condition

              And the difference is previously set a lock can have a monitor method. Now, a Lock can lock multiple sets of monitor method of the object.

              You can implement a responsible producer, a group of responsible consumers.

       The difference --wait and sleep |. ★★★★★

 

      

 

8, stop the thread way.

       | - Principle:

       | - Performance: - interrupt.

 

9, the common thread of some methods.

       | --SetDaemon () daemon threads

       |--join();

       | - priority

       |--yield();

       | - in the development, you can use anonymous inner classes to complete the partial path open.

Published 38 original articles · won praise 6 · views 1929

Guess you like

Origin blog.csdn.net/weixin_43827227/article/details/96606212