7.03_ multithreaded 2

A, Timer categories: Timer

      public class Demo5_Timer {
        /**
        * @param args
        * 计时器
        * @throws InterruptedException
        */
        public static void main(String[] args) throws InterruptedException {
          Timer t = new Timer();
          t.schedule(new MyTimerTask(), new Date(114,9,15,10,54,20),3000);

            while(true) {
              System.out.println(new Date());
              Thread.sleep(1000);
            }
          }
        }
    class MyTimerTask extends TimerTask {
          @Override
          public void run() {
            System.out.println("起床背英语单词");
              }

          }

Second, the communication between two threads

  * 1. When do I need communication
      * when concurrent execution of multiple threads, default CPU is random thread switching
      * If we want them to have to perform regularly, you can use communication, for example, each thread execute a print
  * 2. how communication
      * If you want a thread to wait, call the wait ()
      * If you want to wake up waiting threads, call the Notify ();
      * these two methods must perform a synchronization code, and the use of synchronization lock object to call

Third, the thread communication between three or more
  * issue multiple threads of communication
  * notify () method is a wake-up random thread
  * notifyAll () method wakes up all threads
  * JDK5 not wake up before a specified thread
  * If more than the communication between threads requires use notifyAll () notifies all threads, while repeatedly using the determination condition

Four, JDK1.5 new features mutex

  1. Synchronization *
    * class using the lock ReentrantLock () and synchronization unlock () method
  * 2. Communication
    * class used newCondition ReentrantLock () method gets the object Condition
    * time to wait to use the await of Condition () method, wakeup when using signal () method
    which thread different * different threads Condition, so that we can distinguish between when to wake up to find a

V. Overview and use thread groups  

  * A: Thread Group Overview
    * Java ThreadGroup used to represent the thread group, it can be classified management of a number of threads, Java program allows direct control of the thread group.
    * By default, all threads are belong to the main thread group.
    * Public final ThreadGroup getThreadGroup () // get through the thread object group he belongs
    * public final String getName () // get the name of his group by a thread group object
    * We can also set up groups to a thread
    * 1, ThreadGroup (String name ) creates a thread group object and assign it a value name
    * 2, to create a thread object
    * 3, the thread (ThreadGroup group, Runnable target, String name)???
    * 4, setting the entire set of priority or daemon thread
  * B: case presentation
    * use of thread groups, the default is the main thread group
    *
      MyRunnable new new MyRunnable of Mr = ();
      the thread = T1 new new the thread (of Mr, "John Doe");
      the thread T2 = new new the thread (of Mr, "John Doe");
      // get thread group
      // thread class inside the method: public final ThreadGroup getThreadGroup ()
      TG1 = t1.getThreadGroup of ThreadGroup ();
      of ThreadGroup t2.getThreadGroup TG2 = ();
      // thread group which method: Final public String () getName
      String tg1.getName NAME1 = ();
      String tg2.getName NAME2 = ();
      System.out.println (NAME1);
      System.out.println (NAME2);
      // by the results we know: threads default main thread belonging to the group
      // pass the following test, you should be able to see any default situation under all threads belong to the same group
      System.out.println (Thread.currentThread () getThreadGroup () getName ()..);

  * Set their own thread group
  *
    // ThreadGroup (String name)
    ThreadGroup tg = new new ThreadGroup ( "This is a new group");

    New new MyRunnable of Mr = MyRunnable ();
    // the Thread (Group of ThreadGroup, the Runnable target, String name)
    the Thread new new the Thread = T1 (a Tg of, of Mr, "John Doe");
    the Thread T2 = new new the Thread (a Tg of, of Mr, "John Doe ");

    System.out.println (t1.getThreadGroup () getName ());.
    System.out.println (t2.getThreadGroup () getName ());.

    // set the background thread by group name, indicates that the group thread is a background thread
    tg.setDaemon (true);

Five states six thread

  * New, ready, running, blocking, death

  

Seven Overview and use the thread pool

  * A: Thread Pool Overview
    * program starts a new thread cost is relatively high, as it relates to want to interact with the operating system. When using the thread pool may well improve performance, especially if the program you want to create a large number of short-lived threads should consider using thread pool. After each thread pool thread code that does not die, but returned to the thread pool once again become idle, waiting for the next object to use. Before JDK5, we have to manually implement your own thread pool, start from JDK5, Java support built-in thread pool
  * B: Built-in thread pool Overview
    * JDK5 added a Executors factory class to create a thread pool, there are several methods
    public static ExecutorService newFixedThreadPool * (int nThreads)
    * public static ExecutorService newSingleThreadExecutor ()
    * is the return value of these ExecutorService object that represents a thread pool threads Callable or Runnable object represented by the object may be performed. It provides the following method
    * Future the Submit (Runnable Task) <?>
    * <T> Future <T> the Submit (a Callable <T> Task)
    * Use these steps:
    * Create a thread pool object
    * Create Runnable instance
    * Submit Runnable instance
    * Close thread pool
  * C: case presentation
    * 提交的是Runnable
    *
    // public static ExecutorService newFixedThreadPool(int nThreads)
     ExecutorService pool = Executors.newFixedThreadPool(2);

    // can execute Runnable or Callable object that represents the object thread
    pool.submit (new new MyRunnable ());
    pool.submit (new new MyRunnable ());

    // end of the thread pool
    pool.shutdown ();

Third, the way to achieve multi-threaded program 3

  * Submit a Callable

    *
    // create a thread pool object
    ExecutorService pool = Executors.newFixedThreadPool (2);

    // Runnable object may be executed on behalf of a thread or Callable object
      Future <Integer> = F1 pool.submit (new new MyCallable (100));
      Future <Integer> = F2 pool.submit (new new MyCallable (200 is));

      // V get()
      Integer i1 = f1.get();
      Integer i2 = f2.get();

      System.out.println(i1);
      System.out.println(i2);

      // end
      pool.shutdown ();

    public class MyCallable implements Callable<Integer> {

      int Number Private;

      public MyCallable (int Number) {
      this.number = Number;
    }

      @Override
      public Integer Call () throws Exception {
        int SUM = 0;
        for (int X =. 1; X <= Number; X ++) {
          SUM + the X-=;
          }
          return SUM;
        }

      }
        * way multithreaded program to achieve the benefits and drawbacks of 3
        * benefits:
        * You can have a return value
        * may throw an exception

         drawbacks:
        * code is more complex, it is generally not

Guess you like

Origin www.cnblogs.com/zyyzy/p/12426201.html