• Concurrency Series 1


    Difference between Processes and Threads

    Processes

      A process has a self-contained execution environment. A process generally has a complete, private set of basic run-time resources; in particular, each process has its own memory space.Processes are often seen as synonymous with programs or applications. However, what the user sees as a single application may in fact be a set of cooperating processes. To facilitate communication between processes, most operating systems support Inter Process Communication (IPC) resources, such as pipes and sockets. IPC is used not just for communication between processes on the same system, but processes on different systems.Most implementations of the Java virtual machine run as a single process.

    Threads

      Threads are sometimes called lightweight processes. Both processes and threads provide an execution environment, but creating a new thread requires fewer resources than creating a new process.Threads exist within a process — every process has at least one. Threads share the process's resources, including memory and open files. This makes for efficient, but potentially problematic, communication.Multithreaded execution is an essential feature of the Java platform. Every application has at least one thread — or several, if you count "system" threads that do things like memory management and signal handling. But from the application programmer's point of view, you start with just one thread, called the main thread. This thread has the ability to create additional threads, as we'll demonstrate in the next section.

    Defining and Starting a Thread

    There are two ways to define a thread: One way is to provide a runnable object to the thread constructor.

     1 public class HelloRunnable implements Runnable {
     2 
     3     public void run() {
     4         System.out.println("Hello from a thread!");
     5     }
     6 
     7     public static void main(String args[]) {
     8         (new Thread(new HelloRunnable())).start();
     9     }
    10 
    11 }

    Another way is to extend Thread Class.

     1 public class HelloThread extends Thread {
     2 
     3     public void run() {
     4         System.out.println("Hello from a thread!");
     5     }
     6 
     7     public static void main(String args[]) {
     8         (new HelloThread()).start();
     9     }
    10 
    11 }

    But which one is general? The answer is first noe.Why? Because the Runnable object can subclass a class other than Thread.The second idiom is easier to use in simple applications, but is limited by the fact that your task class must be a descendant of Thread.

    Pausing Execution with Sleep

    Thread.sleep causes the current thread to suspend execution for a specified period. This is an efficient means of making processor time available to the other threads of an application or other applications that might be running on a computer system. The sleep method can also be used for pacing, as shown in the example that follows, and waiting for another thread with duties that are understood to have time requirements, as with the SimpleThreads example in a later section.

    Two overloaded versions of sleep are provided: one that specifies the sleep time to the millisecond and one that specifies the sleep time to the nanosecond. However, these sleep times are not guaranteed to be precise, because they are limited by the facilities provided by the underlying OS. Also, the sleep period can be terminated by interrupts, as we'll see in a later section. In any case, you cannot assume that invoking sleep will suspend the thread for precisely the time period specified.

     1 public class SleepMessages {
     2     public static void main(String args[])
     3         throws InterruptedException {
     4         String importantInfo[] = {
     5             "Mares eat oats",
     6             "Does eat oats",
     7             "Little lambs eat ivy",
     8             "A kid will eat ivy too"
     9         };
    10 
    11         for (int i = 0;
    12              i < importantInfo.length;
    13              i++) {
    14             //Pause for 4 seconds
    15             Thread.sleep(4000);
    16             //Print a message
    17             System.out.println(importantInfo[i]);
    18         }
    19     }
    20 }

    Joins

      The join method allows one thread to wait for the completion of another. If t is a Thread object whose thread is currently executing,  t.join()  causes the current thread to pause execution until t's thread terminates. Overloads of join allow the programmer to specify a waiting period. However, as with sleep, join is dependent on the OS for timing, so you should not assume that join will wait exactly as long as you specify.

    Summary

    The following example brings together some of the concepts of this section. SimpleThreads consists of two threads. The first is the main thread that every Java application has. The main thread creates a new thread from the Runnable object, MessageLoop, and waits for it to finish. If the MessageLoop thread takes too long to finish, the main thread interrupts it.The MessageLoop thread prints out a series of messages. If interrupted before it has printed all its messages, the MessageLoop thread prints a message and exits.

     1 /**  
     2  * @Title: SimpleThreads.java
     3  * @Package books.the_java_tutorials.concurrency
     4  * @author "Never" xzllc2010#gmail.com  
     5  * @date Mar 15, 2014 3:54:35 PM
     6  * @Description: The following example brings together some of the 
     7  *     concepts of this section. SimpleThreads consists of two threads. 
     8  *     The first is the main thread that every Java application has. 
     9  *     The main thread creates a new thread from the Runnable object, 
    10  *     MessageLoop, and waits for it to finish. If the MessageLoop thread 
    11  *     takes too long to finish, the main thread interrupts it. The 
    12  *     MessageLoop thread prints out a series of messages. If interrupted 
    13  *     before it has printed all its messages, the MessageLoop thread 
    14  *     prints a message and exits.
    15  */
    16 package books.the_java_tutorials.concurrency;
    17 
    18 public class SimpleThreads {
    19 
    20     // Display a message, preceded by
    21     // the name of the current thread
    22     static void threadMessage(String message) {
    23         String threadName = Thread.currentThread().getName();
    24         System.out.format("%s: %s%n", threadName, message);
    25     }
    26 
    27     private static class MessageLoop implements Runnable {
    28         public void run() {
    29             String importantInfo[] = { "Mares eat oats", "Does eat oats", "Little lambs eat ivy", "A kid will eat ivy too" };
    30             try {
    31                 for (int i = 0; i < importantInfo.length; i++) {
    32                     // Pause for 4 seconds
    33                     Thread.sleep(4000);
    34                     // Print a message
    35                     threadMessage(importantInfo[i]);
    36                 }
    37             } catch (InterruptedException e) {
    38                 
    39                 try {
    40                     Thread.sleep(5000);
    41                 } catch (InterruptedException e1) {
    42                     e1.printStackTrace();
    43                 }
    44                 threadMessage("I wasn't done!");
    45             }
    46         }
    47     }
    48 
    49     public static void main(String args[]) throws InterruptedException {
    50 
    51         // Delay, in milliseconds before
    52         // we interrupt MessageLoop
    53         // thread (default one hour).
    54         long patience = 1000 * 10;
    55 
    56         // If command line argument
    57         // present, gives patience
    58         // in seconds.
    59         if (args.length > 0) {
    60             try {
    61                 patience = Long.parseLong(args[0]) * 1000;
    62             } catch (NumberFormatException e) {
    63                 System.err.println("Argument must be an integer.");
    64                 System.exit(1);
    65             }
    66         }
    67 
    68         threadMessage("Starting MessageLoop thread");
    69         long startTime = System.currentTimeMillis();
    70         Thread t = new Thread(new MessageLoop());
    71         t.start();
    72 
    73         threadMessage("Waiting for MessageLoop thread to finish");
    74         // loop until MessageLoop
    75         // thread exits
    76         while (t.isAlive()) {
    77             threadMessage("Still waiting...");
    78             // Wait maximum of 1 second
    79             // for MessageLoop thread
    80             // to finish.
    81             t.join(1000);
    82             if (((System.currentTimeMillis() - startTime) > patience) && t.isAlive()) {
    83                 threadMessage("Tired of waiting!");
    84                 t.interrupt();
    85                 // Shouldn't be long now
    86                 // -- wait indefinitely
    87                 //t.join();
    88             }
    89         }
    90         threadMessage("Finally!");
    91     }
    92 }

    Where's the time?

     写的时候突然想起了这首歌,这么年轻就有点感触,嗨,老了吧。

  • 相关阅读:
    团队作业2-《需求规格说明书》
    团队作业 —— 团队选题
    自我介绍+软工五问
    团队作业5——测试与发布(Alpha版本)
    结对项目(与陈超国)
    个人项目wordcount
    自我介绍+软工5问
    个人项目(C语言)
    自我介绍+软工五问
    第三篇 Scrum冲刺博客
  • 原文地址:https://www.cnblogs.com/RobertC/p/3602053.html
Copyright © 2020-2023  润新知