java study notes: Multithreaded 2

1, lock and lock overview of the use of
a, Overview: While we can understand the problem of synchronization lock object code block and synchronization method, but we do not directly see where to add a lock, where the lock is released, in order to more clearly the expression of how lock and release the lock, JDK1.5 later provide a new lock object lock
b, lock and ReentrantLock

  • ReentrantLock: a reentrant mutex Lock, having a lock implicit monitor using synchronized methods and statements accessed the same basic behavior and semantics, but more powerful.
  • Lock: implementations provide more extensive locking available than synchronized methods and statements operation. This implementation allows a more flexible structure, can have very different properties, can support multiple associated Condition objects.

c, Lock locks use

public class MyThread implements Runnable { 	    	
	private static int tickets = 100 ;	// 定义票数  
    private static final Lock lock = new ReentrantLock() ;  // 创建Lock锁对象
    @Override
	public void run() {		
	while(true){			
		lock.lock() ;	// 添加锁		
		if(tickets > 0){				
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}				
			System.out.println(Thread.currentThread().getName() + "正在出售" + (tickets--) + "张票");				
		}			
		lock.unlock() ;	// 释放锁		
	}		
  }
}
public class MyThreadDemo {
  	public static void main(String[] args) {		
	   // 创建MyThread类的对象
	   MyThread mt = new MyThread() ;		
    	// 创建3个线程对象
	   Thread t1 = new Thread(mt , "窗口1") ;
	   Thread t2 = new Thread(mt , "窗口2") ;
	   Thread t3 = new Thread(mt , "窗口3") ;		
	   // 启动线程
	   t1.start() ;
	   t2.start() ;
	   t3.start() ;				
    }
}

2, an overview of the deadlock problem and use
a, Overview: When a synchronization nested, can easily cause deadlock problem, each refers to a two or more threads in the implementation of the process, due to the competition for resources generated waiting for the phenomenon.
Deadlock: two or more threads at the time to seize the execution of the CPU's, are in a wait state
b, case presentations

class ObjectUtils {
    //定义两把锁
    public static final Object objA=new Object();
    public static final Object objB = new Object();
}
class MyThread extends Thread {
boolean flag;
public MyThread(boolean flag) {
    this.flag = flag;
}
@Override
public void run() {
    if (flag) {
        synchronized (ObjectUtils.objA) {
            System.out.println("true 进来了 持有objA");
            try {
                sleep(10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //阻塞
            synchronized (ObjectUtils.objB) {
                System.out.println("true 进来了 持有objB");
            }
        }
    } else {
        synchronized (ObjectUtils.objB) {
            System.out.println("false 进来了 持有objB");
            //阻塞
            synchronized (ObjectUtils.objA) {
                System.out.println("false 进来了 持有objA");
            }
         }
     }
  }
}
public class MyDemo {
   public static void main(String[] args) throws InterruptedException {
      MyThread th1 = new MyThread(true);
      MyThread th2 = new MyThread(false);
      th1.start();
      th2.start();
  }
}
输出结果:true 进来了 持有objA
         false 进来了 持有objB
原因:在执行了第一条程序后,相互持有了对方的锁而未释放,导致程序发生阻塞不能往下执行

3, wait for the wake-up mechanism between threads
once the wait, we must immediately release the lock, then was traded the next wake up, wake up from where from where to wait.

  • void wait (); // call this object before in other threads notify () method or the notifyAll () method causes the current thread to wait.
  • void wait (long timeout); // call this object before in other threads notify () method or the notifyAll () method, or a specified amount of time, leading to the current thread to wait.
  • void notify (); // wake up a single thread waiting on this object's monitor.
  • void notifyAll (); // wake up all threads waiting on this object's monitor.

the difference between sleep and wait method method: it is possible to make a thread is blocked
sleep () must be passed in the amount of time; wait time can pass or not pass the amount of time the amount of
sleep () after the thread to sleep, do not release the lock; wait () method once we must wait for the release of the lock
4, state transition diagrams and the common thread of the implementation of
the new: the thread is created
ready: a qualified execution of the CPU, but the CPU does not have executive powers
to run: a CPU is eligible to perform, also has a CPU execution right
obstruction: CPU does not have the qualifications to perform, nor has the executive power of the CPU
death: CPU does not have the qualifications to perform, nor has the executive power of the CPU
Here Insert Picture Description
5, and an overview of the use of the thread pool
a, Overview: a container, inside pre-loaded thread object, and efficient management can help us thread object, manually create our own thread, it is the underlying resource consuming, and after the thread used up, the death, and can not be reused; after JDK1.5 has given we offer a good thread pool, we only need to submit the task to the thread pool inside.

  • Gets the thread pool object, Java provides us with a factory, with the factory class to get to the thread pool objects

  • ExecutorService executorService = Executors.newCachedThreadPool();

  • JDK5 added Executors factory class to generate a thread pool, there are several methods as follows

  • public static ExecutorService newCachedThreadPool (); to create a number of threads in the task corresponding to the number of

  • public static ExecutorService newFixedThreadPool (int nThreads); fixed initialization few threads

  • public static ExecutorService newSingleThreadExecutor (); initialize a thread pool thread

b, for example:

 public class MyDemo {
     public static void main(String[] args) {
     //获取线程池对象
        ExecutorService executorService = Executors.newCachedThreadPool();
        //往线程池中提交任务
        MyRuannable myRuannable = new MyRuannable();
        MyRuannable myRuannable2 = new MyRuannable();
        MyRuannable myRuannable3 = new MyRuannable();
        MyRuannable myRuannable4 = new MyRuannable();
        executorService.submit(myRuannable);
        executorService.submit(myRuannable2);
        executorService.submit(myRuannable3);
        executorService.submit(myRuannable4);
        //关掉线程池 
        executorService.shutdown();    
      }
  }
class MyRuannable implements Runnable{
    @Override
    public void run() {
       System.out.println(Thread.currentThread().getName()+"任务执行了");
    }
}

6, anonymous inner class way to achieve multi-threaded programs

public class MyDemo3 {
    public static void main(String[] args) {
        //匿名内部类来创建线程
        //方式1
        new Thread() {
            @Override
            public void run() {
                System.out.println("线程执行了");
            }
        }.start();
        //方式2:
        Runnable runnable = new Runnable() {
            @Override
            public void run() {
                System.out.println("线程执行了");
            }
        };
        new Thread(runnable) {
        }.start();
    }
}

7, a timer and an overview of the use of
a, Overview: Timer is a very broad application of threading tools, can be used for future scheduling multiple timing tasks performed in a manner background thread. In Java, the definition of a schedule may be implemented by the function Timer and TimerTask classes.
b, Timer and TimerTask

  • The Timer:
    public the Timer () // create a new timer
    public void schedule (TimerTask task, long delay); // Schedules the specified task after a specified delay
    public void schedule (TimerTask task, long delay, long period); / / Schedules the specified task from the start after a specified delay for repeated fixed-delay execution.
    public void schedule (TimerTask task, Date time); // scheduled to perform specified tasks at a specified time.
    public void schedule (TimerTask task, Date firstTime, long period); // the specified task schedule repeated at the specified time a fixed delay execution.
  • TimerTask
    public abstract void RUN (); // operation to be performed by this timer task.
    public boolean cancel (); // Cancels this timer task.

c, case presentations

定时任务的多次执行代码体现
定时删除指定的带内容目录
public class MyDemo {
    public static void main(String[] args) throws ParseException {
        Timer timer = new Timer();//创建定时器
        MyTimerTask task = new MyTimerTask(timer);
        //timer.schedule(task,2000); //参数1 定时任务,参数 等待多少毫秒后执行
       // timer.schedule(task,2000,1000);//连环爆炸
        task.cancel(); 取消定时任务
        //指定日期去执行任务
        String dateStr="2019-01-20 13:46:00";
        Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(dateStr);
       // timer.schedule(task,date,1000*60*60*24*30);
    }
}
class MyTimerTask extends TimerTask{
    Timer timer;
    public MyTimerTask(Timer timer) {
        this.timer=timer;
    }
    @Override
    public void run() {
       // System.out.println("砰~~~爆炸了");
       // timer.cancel(); //关闭定时器
    }
}
Published 24 original articles · won praise 11 · views 2049

Guess you like

Origin blog.csdn.net/weixin_43791069/article/details/86684478