2021-02-19Java Learning Record

Java basics (short answer)------Multithreading (decorating synchronization methods? Why stop() and suspend() methods are not recommended?)

  • stop(), because it is not safe. It releases all locks acquired by the thread, and if the object is in an incoherent state, then other threads can check and modify them in that state. As a result, it is difficult to detect the real problem.
  • The suspend() method is prone to deadlock. When suspend() is called, the target thread will stop, but it still holds the lock obtained before that. At this time, no other thread can access the locked resource unless the "suspended" thread resumes operation. For any thread, if they want to restore the target thread while trying to use any locked resource at the same time, it will cause a deadlock. Therefore, suspend() should not be used, but a flag should be placed in your Thread class to indicate whether the thread should be active or suspended. If the flag indicates that the thread should be suspended, use wait() to order it to enter the waiting state. If the flag indicates that the thread should be resumed, a notify() is used to restart the thread.

Java basics (short answer)------multithreading (what is the difference between sleep() and wait()?)

  • Sleep is a method of the thread class (Thread), which causes this thread to suspend execution for a specified time, giving execution opportunities to other threads, but the monitoring state is still maintained and will automatically resume after that time. Calling sleep will not release the object lock.
  • Wait is a method of the Object class. Calling the wait method on this object causes the thread to give up the object lock and enter the waiting lock pool waiting for this object. Only after the notify method (or notifyAll) is issued for this object, the thread enters the object lock pool and prepares to obtain it. The object lock enters the running state.

Java Basics (Short Answer)------Multithreading (Briefly describe the similarities and differences between synchronized and java.util.concurrent.locks.Lock?)

  • The main similarity : Lock can complete all the functions realized by synchronized
  • The main difference : Lock has more precise thread semantics and better performance than synchronized.synchronized will automatically release the lock,andLock must be manually released by the programmer, and must be released in the finally clause

Java basics (exercises)------multithreading (simulating bank withdrawal problems)

Insert picture description here
Account class

public class Account {
    
    
	private String idString;
	private double balance;

	public Account() {
    
    
		super();
	}
	public Account(String idString, double balance) {
    
    
		super();
		this.idString = idString;
		this.balance = balance;
	}
	public String getIdString() {
    
    
		return idString;
	}
	public void setIdString(String idString) {
    
    
		this.idString = idString;
	}
	public double getBalance() {
    
    
		return balance;
	}
	public void setBalance(double balance) {
    
    
		this.balance = balance;
	}
	@Override
	public int hashCode() {
    
    
		final int prime = 31;
		int result = 1;
		result = prime * result + ((idString == null) ? 0 : idString.hashCode());
		return result;
	}
	@Override
	public boolean equals(Object obj) {
    
    
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Account other = (Account) obj;
		if (idString == null) {
    
    
			if (other.idString != null)
				return false;
		} else if (!idString.equals(other.idString))
			return false;
		return true;
	}
	@Override
	public String toString() {
    
    
		return "Account [idString=" + idString + ", balance=" + balance + "]";
	}
	
	

}

Test class
Insert picture description here

Java (Dug)------eclipse mouse becomes a cross solution

  • Use shortcut keys:alt+shift+a

Java basics (exercises)------multithreading (the problem of the tortoise and the hare)

/*
 * 编写龟兔赛跑多线程程序,设赛跑长度为100米,每跑完10米输出一次结果。
改进上题的龟兔赛跑程序,通过改变优先级,
并减掉休眠时间,使得乌龟以迅雷不及掩耳的速度跑完100米。
 */


public class Demo5 {
    
    
	public static void main(String[] args) {
    
    
		TortoiseRun tesTortoiseRun = new TortoiseRun();
		RabbitRun testRabbitRun  = new RabbitRun();
		
		Thread t1 = new Thread(tesTortoiseRun);
		Thread t2 = new Thread(testRabbitRun);
		t1.setName("乌龟");
		t2.setName("兔子");
		t1.start();
		t2.start();
		
	}

}
//乌龟跑100米
class TortoiseRun implements Runnable{
    
    
	int journey = 100;
	
	@Override
	public void run() {
    
    
		synchronized (this) {
    
    
			for(int i = 0;i <= 100;i++) {
    
    
				try {
    
    
					Thread.sleep(20);
				}catch(InterruptedException e) {
    
    
					e.printStackTrace();
				}
				if(i==10 || i==20||i==30 || i==40||i==50 || i==60||i==70 || i==80||i==90 || i==100) {
    
    
					System.out.println(Thread.currentThread().getName() +"跑了" + i + "米");
				}
			}	
		}
	}
}
class RabbitRun implements Runnable{
    
    
	
	int journey = 100;
	@Override
	public void run() {
    
    
		synchronized (this) {
    
    
			for(int i = 0;i <= 100;i++) {
    
    
				try {
    
    
					Thread.sleep(50);
				}catch(InterruptedException e) {
    
    
					e.printStackTrace();
				}
				if(i==10 || i==20||i==30 || i==40||i==50 || i==60||i==70 || i==80||i==90 || i==100) {
    
    
					System.out.println(Thread.currentThread().getName() +"跑了" + i + "米");
				}
			}
		}
	}	
}


Test Results
Insert picture description here

Java Basics (Exercises)------Multithreading (Selection of Synchronous Monitor)

/*
 * 启动两个线程对一个数字i操作
 *1)其中1个线程每次对i加1
 *2)另1个线程每次对i减1
 *各运行20次,结果i的值等于初始值。
 */
public class Demo6 {
    
    
	public static void main(String[] args) {
    
    
		number num = new number(20);
		Add add = new Add(num);
		Sub sub = new Sub(num);
		Thread t1 = new Thread(add);
		Thread t2 = new Thread(sub);
		t1.setName("+1操作:");
		t2.setName("-1操作:");
		t1.start();
		t2.start();
//		try {
    
    
//			t1.join(15);
//		}catch (InterruptedException e) {
    
    
//			e.printStackTrace();
//		}
//		try {
    
    
//			t2.join(14);
//		} catch (InterruptedException e) {
    
    
//			e.printStackTrace();
//		}
	}

}
class number{
    
    
	private static int i;
	public number(int i) {
    
    
		this.i = i;
	}
	public int getI() {
    
    
		return i;
	}
	public void setI() {
    
    
		this.i =i;
	}
	public void sub() {
    
    
		i--;
	}
	public void add() {
    
    
		i++;
	}
}

class Add implements Runnable{
    
    
	private number num;
	public Add(number num) {
    
    
		this.num = num;
	}
	public void run() {
    
    
		synchronized (num) {
    
    
			for(int j = 0; j < 20; j++){
    
    
				
				try {
    
    
					Thread.sleep(20);
				}catch(InterruptedException e) {
    
    
					e.printStackTrace();
				}
				num.add();
				System.out.println(Thread.currentThread().getName() + "对i+1后,i 的值为:" + num.getI());
			}
		}
	}
	
}
class Sub implements Runnable{
    
    
	private number num;
	public Sub(number num) {
    
    
		this.num = num;
	}
	@Override
	public void run() {
    
    
		synchronized (num) {
    
    
			for(int j = 0; j < 20; j++){
    
    
				try {
    
    
					Thread.sleep(20);
				}catch(InterruptedException e) {
    
    
					e.printStackTrace();
				}
				num.sub();
				System.out.println(Thread.currentThread().getName() + "对i-1后,i 的值为:" + num.getI());
			}
		}
	}
}

Here, the number i should be encapsulated in another Number class as an attribute, and objects of the Number class should be used as a synchronization monitor, so that multiple threads can share a synchronization monitor.

Java basics (exercises)------Multithreading (notify(), wait() methods can ensure that threads cannot print continuously)

/*
 * 实现一个由A、B、C三个窗口同时销售100张票的系统,
 * 要求打印出每个窗口打印的售票情况,并且每个窗口不得连续售票
 */

public class Demo7 {
    
    
	public static void main(String[] args) {
    
    
		windows testWindows = new windows();
		Thread t1 = new Thread(testWindows);
		Thread t2 = new Thread(testWindows);
		Thread t3 = new Thread(testWindows);
		t1.setName("窗口一");
		t2.setName("窗口二");
		t3.setName("窗口三");
		t1.start();
		t2.start();
		t3.start();
	}
	

}
class windows implements Runnable{
    
    
	private static int titck = 1;
	
	@Override
	public void run() {
    
    
		while(titck < 99) {
    
    
			synchronized (this) {
    
    
				this.notify();
				
				try {
    
    
					Thread.sleep(10);
				}catch(InterruptedException e) {
    
    
					e.printStackTrace();
				}
				System.out.println(Thread.currentThread().getName() + "票号为:" + titck);
				titck++;
				try {
    
    
					this.wait();
				}catch (InterruptedException e) {
    
    
					e.printStackTrace();
				}
			
			}
		}
						
	}
}

Guess you like

Origin blog.csdn.net/m0_51755061/article/details/113859574