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

table of Contents

Part IV: communication between threads

Wait wake-up mechanism

Example: Multi-producers and more consumers question

Optimization: new features Lock, Condition

wait and sleep difference?

Stop Thread

Daemon thread


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

Part IV: communication between threads

The concept: multiple threads in the same process resources, but the task is different. (With a bank, it was to save money, some people withdraw money)

 

Wait wake-up mechanism

The method involves:

1, wait (): make a thread in a frozen state, the wait thread will be stored in the thread pool.

2, notify (): wake up a thread pool thread (arbitrary).

3, notifyAll (): wake up all the threads in the thread pool.

 

Why are these methods must be defined in the synchronization?

Because the method is a method for operating a thread state. We must be clear in the end of the operation which is locked thread.

 

Why method of operating a thread wait notify notifyAll defined in the Object class?

Because these methods are methods monitor. In fact monitor lock: Synchronized (ie, the object lock).

The lock may be any object, of any object is defined in a certain manner called Object class.

 

process:

example:

//用等待唤醒注意点: 1, 同步函数             2,wait和notify成对
//wait,notify,notifyAll这些方法都必须定义在同步中
	public synchronized void set(String name,String sex)
	{
		if(flag)
			try{this.wait();}catch(InterruptedException e){}
		this.name = name;
		this.sex = sex;
		flag = true;
		this.notify();
	}

Example: Multi-producers and more consumers question

if the decision marks only once, causes the thread should run to run. There has been a data error.

while judging flag, resolved after the thread gets executed right, if you want to run!

 

notify: wake up only one thread, (multiple set) if the party wake of the party, does not make sense. And while the decision marks + notify will result in a deadlock (performed while waking judgment, wait again, all threads wait, then a deadlock).

 

notifyAll solve the problem of the party thread will wake up the other thread.

(However, this method not only wake up the other side, they wake up the party, while making judgment, reducing the efficiency of .JDK1.5 this optimized)

Currently Conclusion: produce more and more consumption, with the judge while awake and notifyAll

Drawbacks: not only wake up the other side, wake up the party, while making judgment, reducing the efficiency

class Resource2 {
	private String nameString="烤鸭";
	private int count =1;
	private boolean flag =false;
//	Lock lock=new ReentrantLock();
//	Condition condition =lock.newCondition();
	
	public synchronized void set(String name) {
		while(flag)     
			//if判断标记,只有一次,会导致不该运行的线程运行了。出现了数据错误的情况。
			//while判断标记,解决了线程获取执行权后,是否要运行!
			//notify:只能唤醒一个线程,如果本方唤醒了本方,没有意义。而且while判断标记+notify会导致死锁。
			
			//结论:多生产多消费时,用while 和 notifyAll进行判断与唤醒
			//弊端:既唤醒对方,又唤醒本方,在进行while判断,降低了效率
			try {
				this.wait();
			} catch ( InterruptedException e) {
			}
		count=count+1;
		System.out.println(Thread.currentThread().getName()+"。。。。。生产者。。。。。"+this.nameString+count);
		flag=true;
		notifyAll();  //notifyAll解决了本方线程一定会唤醒对方线程的问题。
	}
	
	public synchronized void out() {//与上面的格式进行对比
//		lock.lock();
		try {
			while(!flag)
				try {
					this.wait();
				} catch ( InterruptedException e) {
				}
			System.out.println(Thread.currentThread().getName()+"。。。。。。。。消费者。。。。。。"+this.nameString+count);
			flag=false;
			notifyAll();
		} finally {
//			lock.unlock();
		}
	}
}

class Producer2 implements Runnable{
	private Resource2 r;   //传递参数      创建资源对象,然后传递给set out
	Producer2(Resource2 r)
	{
		this.r = r;
	}
	public void run()
	{
		while(true)
		{
			r.set("烤鸭");
		}
	}
}

class Consumer implements Runnable
{
	private Resource2 r;    //传递参数      创建资源对象,然后传递给set out 
	Consumer(Resource2 r)
	{
		this.r = r;
	}
	public void run()
	{
		while(true)
		{
			r.out();
		}
	}
}


public class ProducerConsumerDemo {
	public static void main(String[] args) {
		Resource2 resource2 =new Resource2();
		
		Producer2 producer2=new Producer2(resource2);
		Consumer consumer=new Consumer(resource2);
		
		Thread t1=new Thread(producer2);
		Thread t2=new Thread(producer2);
		Thread t3=new Thread(consumer);
		Thread t4=new Thread(consumer);
		
		t1.start();
		t2.start();
		t3.start();
		t4.start();
		
	}
}

 

 

 

 

---------------------------------------------------------------------------------------------------------------------------------------------

Optimization: new features Lock, Condition

Lock replacement synchronized

Alternative methods to those Condition Monitor (object in the wait, notify, and notifyAll)

---------------------------------------------------------------------------------------------------------------------------------------------

Difference: before the synchronization code and the synchronization function blocks are only the package, comes with lock (lock operations: acquisition, release is implicit, not visible).

           Now the lock object is encapsulated into a Lock: Providing the lock () and unlock () methods i.e. acquire and release locks two of

          And any combination of the lock may be

 

------------------------------------------------------------------------------

-------------------------------------------------------------------------------

https://img-blog.csdnimg.cn/2019072312442060.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80MzgyNzIyNw==,size_16,color_FFFFFF,t_70 ​​

 

Lock lock=new ReentrantLock();
Condition condition =lock.newCondition();

public synchronized void out() {
		while(!flag)
			try {
				//this.wait();
                        condition.await  ();
			} catch ( InterruptedException e) {
			}
		this.nameString =nameString+count;
		System.out.println(Thread.currentThread().getName()+"。消费者。。。。。。"+this.nameString);
		flag=false;
		//notifyAll();
                condition.signalAll();
	}

//这样子功能没有变化,与之前一致。
//------------------------------------------------
//下面是优化后
	
//若通过已有的锁获取两组监视器,一组监视生产者,一组监视消费者。(则可体现优化所在:一个锁可以显加上多组监视器)
	Condition producer_con = lock.newCondition();//监听生产者
	Condition consumer_con = lock.newCondition();//监听消费者

public  void out() {//与上面的格式进行对比
		lock.lock();
		try {
			while(!flag)
				try {
					consumer_con.await(); //指定沉睡一个消费者的线程
				} catch ( InterruptedException e) {
				}
			System.out.println(Thread.currentThread().getName()+"。消费者。。。。。。"+this.nameString+count);
			flag=false;
			producer_con.signal();//指定唤醒一个生产者的线程
		} finally {
			lock.unlock();
		}
	}

 


wait and sleep difference?

1, wait the specified time may or may not be specified.
   sleep time must be specified.

2, when the synchronization, the execution right of the cpu and handle different locks.
    wait: the release of the implementation of the right to release the lock.
    sleep: the release of executive power, not to release the lock.
 

Stop Thread

The end of the run method.

How threads of control tasks end?
Mission will have a loop structure, as long as you can control the cycle ending task.

Control cycle usually is accomplished by the definition of tag.

 

But if the thread is in a frozen state, can not read the label. How to end it?

You can use interrupt () method will be forced to resume the thread running from the frozen state to state in the past, so that the thread of execution with cpu qualifications. 

But the forced action will occur the InterruptedException, remember to handle

 

Daemon thread

Can be understood as a background thread, the end of the foreground thread, the thread daemon (background thread) ended automatically.

 

 

Thread priority

t2.setPriority(Thread.MAX_PRIORITY);

The default priority is to create a thread 5 (1-10, the more favorable the greater priority, but also need to seize the CPU resources)

 

 

 

 

Published 38 original articles · won praise 6 · views 1928

Guess you like

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