Dark Horse Programmer--java Basic Day24 Multi-threading, deadlock, inter-thread communication, thread group, threads pool, timers.

Source: Internet
Author: User
Tags stub try catch

-------Android Training, Java training, look forward to communicating with you! ----------

    1. The lock () implementation provides a wider range of locking operations than using synchronized methods and statements.

    2. Private lock Lock =new reentrantlock ();

    3. The code to be locked is included with Lock.lock () Lock.unlock (). One with Try ... Finally surround

    4. Synchronization: Low efficiency, deadlock occurs if synchronous nesting occurs. But safe.

    5. Deadlock problem: Two or more than two threads in the process of contention for resources, a kind of mutual waiting phenomenon occurred

    6. Inter-thread communication, the operation of different kinds of threads against the same resource.

    7. Multithreading can also occur multiple times with the same data, or output mismatch problems. are thread-safe issues.

    8. Wait for wake-up mechanism

    9. Wait () in the object class waits for Notify () to wake up a single thread notifyall () wakes all threads

    10. These method calls must be called through the lock object, and the lock object we just used is an arbitrary lock object.
      Wait () to be surrounded by a try catch with Wake notify () to resolve the deadlock

      That is, a run () determines a condition if it is set on a lock call to wait (), if not set, the lock's judging condition changes and then calls notify () to wake up.

    11. Run state diagram:

    12. Thread groups: The main thread GROUP by default
      Getthreadgroup () Get thread Group
      Thread.CurrentThread (). Getthreadgroup (). GetName (); Returns the name of the thread group.

    13. Changing thread groups
      First create a thread group: Threadgroup tg=new Threadgroup ("This is a new thread group");

      Then thread t1=new thread (Tg,myrunnale, "thread name");

    14. Set a background thread through the thread group name, Tg.setdaemon () sets the daemon thread. Wait a minute

      Thread groups are primarily thread-unified management.

    15. Synchronization can also be in the class, the corresponding method is set to synchronized note the lock object inside the method is this

    16. Thread Pool: Program startup A new thread cost is relatively high because it involves interacting with the operating system, and two using the thread pool can improve performance, especially if you want to consider using thread pooling when you are creating a lot of short-lived threads in your program.

    17. The thread pool will not be destroyed when it ends, but back to the thread pool to become idle.

    18. static ExecutorService newCachedThreadPool()
      Create a thread pool that can create new threads as needed, but reuse them when previously constructed threads are available.
    19. static ExecutorService newFixedThreadPool(int nThreads)
      Create a thread pool that reuses the number of fixed threads and run them in a shared, unbounded queue.
    20. static ExecutorService newSingleThreadExecutor()
      Create a Executor that uses a single worker thread to run the thread in a unbounded queue.

    21. A: Create a thread pool object that controls the creation of several thread objects
      Executorservoce newfixedthreadpool (int nthread)
      B: Threads of this thread pool can execute:
      Can execute Runnable object or thread represented by callable object
      Make an implementation runnable interface
      C: Call the following method:
      Future<?> Submit (Runnable Task)
      <T> future<t> Submit (callable<t> Task)

    22. Newfixedthreadpool static functions, calling directly

    23. 1 executorservice pool=executors.newfixedthreadpool (2); 2 pool.submit (new myrunnable);

    24. End thread pool: Pool.shutdown ();
    25. Create multithreaded Mode 3:
      Callable is an interface this line threads returns an interface, but Runnable does not return a result. Similar to runnable usage
      He is creating threads through the line pool. It's not common.
    26. The future represents the result of the submit asynchronous calculation. It provides a way to check whether the calculation is complete, to wait for the calculation to complete, and to get the results of the calculation. You can only use the get method to get the results after the calculation is complete and, if necessary, block this method before the calculation is complete.                    Cancellation is performed by the cancel method. Trouble, generally not.
    27. Anonymous internal classes use multithreading "
      1 //integrating the thread class to implement multithreading2 NewThread () {3 Public voidrun () {4 for(inti = 0; I < 100; i++) {5System.out.println (Thread.CurrentThread (). GetName () + ":" +i);6                 }7             };8 }.start ();9//implemented with runnable interfaceTenNewThread (NewRunnable () { One    A @Override - Public voidrun () { -//TODO auto-generated Method Stub the for(inti = 0; I < 100; i++) { -System.out.println (Thread.CurrentThread (). GetName () + ":" +i); -                 } -             } +}) {}.start ();
    28. But for, the child that walks is, will output world, will not output hello
      1 NewThread (NewRunnable () {2   3 @Override4 Public voidrun () {5//TODO auto-generated Method Stub6 for(inti = 0; I < 100; i++) {7System.out.println ("Hello" + ":" +i);8         }9     }Ten }){ One Public voidrun () { A for(inti = 0; I < 100; i++) { -SYSTEM.OUT.PRINTLN ("World" + ":" +i); -         } the     }; -}.start ();
    29. To do something or to repeat something at a specified time.

      Timer a tool that a thread uses to schedule tasks to perform later in a background thread. You can schedule a task to execute once, or repeat it periodically.

    30. Two classes of timer and TimerTask dependent
      Timer Timer
      TimerTask: Task
    31. ? Construction Method Summary
      Timer()
      Creates a new timer.
    32. Timer method

      cancel()
      Terminates this timer, discarding all currently scheduled tasks.
       int purge()
      Removes all canceled tasks from this timer's task queue.
       void schedule(TimerTask task, Date time)
      Schedules the specified task to execute at the specified time.
       void schedule(TimerTask task, Date firstTime, long period)
      Schedules the specified task to begin repeating fixed deferred execution at a specified time.
       void schedule(TimerTask task, long delay)
      Schedules the specified task to execute after a specified delay.
       void schedule(TimerTask task, long delay, long period)
      Schedules the specified task to start repeating fixed deferred execution from the specified delay.
       void scheduleAtFixedRate(TimerTask task, Date firstTime, long period)
      Schedules the specified task to start at a fixed rate of repetition at a specified time.
       void scheduleAtFixedRate(TimerTask task, long delay, long period)
      Schedules the specified task to begin repeating a fixed rate of execution after a specified delay.

    33. Interview questions
      1: There are several implementations of multithreading, which are the different?two kinds. Inheriting the thread class implements a runnable interface extension: implements the callable interface. This has to be combined with the thread pool. 2: There are several ways to sync, what are the differences?two kinds. Synchronous code block synchronization method3: Start a thread is run () or start ()? What are their differences?start (); Run (): encapsulates the code executed by the thread, calling only the normal method call Start (): Starting the thread and automatically invoking the run () method by the JVM4: The difference between the sleep () and wait () methods sleep (): must refer to time; Wait (): You can specify a time or time, or release a lock. 5: Why Wait (), notify (), Notifyall () are defined in the object class because the calls to these methods are dependent on the lock object, and the lock object of the synchronous code block is any lock. and object code arbitrary objects, so, defined in this face. 6: Thread's life cycle diagram new--ready--run--Death New--ready--run--block--ready--run--Death advice: drawing explanations. 

Dark Horse Programmer--java Basic Day24 Multi-threading, deadlock, inter-thread communication, thread group, threads pool, timers.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.