Concurrency Series 1

时间:2022-05-02 18:42:50

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.

 public class HelloRunnable implements Runnable {

     public void run() {
System.out.println("Hello from a thread!");
} public static void main(String args[]) {
(new Thread(new HelloRunnable())).start();
} }

Another way is to extend Thread Class.

 public class HelloThread extends Thread {

     public void run() {
System.out.println("Hello from a thread!");
} public static void main(String args[]) {
(new HelloThread()).start();
} }

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.

 public class SleepMessages {
public static void main(String args[])
throws InterruptedException {
String importantInfo[] = {
"Mares eat oats",
"Does eat oats",
"Little lambs eat ivy",
"A kid will eat ivy too"
}; for (int i = 0;
i < importantInfo.length;
i++) {
//Pause for 4 seconds
Thread.sleep(4000);
//Print a message
System.out.println(importantInfo[i]);
}
}
}

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.

 /**
* @Title: SimpleThreads.java
* @Package books.the_java_tutorials.concurrency
* @author "Never" xzllc2010#gmail.com
* @date Mar 15, 2014 3:54:35 PM
* @Description: 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.
*/
package books.the_java_tutorials.concurrency; public class SimpleThreads { // Display a message, preceded by
// the name of the current thread
static void threadMessage(String message) {
String threadName = Thread.currentThread().getName();
System.out.format("%s: %s%n", threadName, message);
} private static class MessageLoop implements Runnable {
public void run() {
String importantInfo[] = { "Mares eat oats", "Does eat oats", "Little lambs eat ivy", "A kid will eat ivy too" };
try {
for (int i = 0; i < importantInfo.length; i++) {
// Pause for 4 seconds
Thread.sleep(4000);
// Print a message
threadMessage(importantInfo[i]);
}
} catch (InterruptedException e) { try {
Thread.sleep(5000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
threadMessage("I wasn't done!");
}
}
} public static void main(String args[]) throws InterruptedException { // Delay, in milliseconds before
// we interrupt MessageLoop
// thread (default one hour).
long patience = 1000 * 10; // If command line argument
// present, gives patience
// in seconds.
if (args.length > 0) {
try {
patience = Long.parseLong(args[0]) * 1000;
} catch (NumberFormatException e) {
System.err.println("Argument must be an integer.");
System.exit(1);
}
} threadMessage("Starting MessageLoop thread");
long startTime = System.currentTimeMillis();
Thread t = new Thread(new MessageLoop());
t.start(); threadMessage("Waiting for MessageLoop thread to finish");
// loop until MessageLoop
// thread exits
while (t.isAlive()) {
threadMessage("Still waiting...");
// Wait maximum of 1 second
// for MessageLoop thread
// to finish.
t.join(1000);
if (((System.currentTimeMillis() - startTime) > patience) && t.isAlive()) {
threadMessage("Tired of waiting!");
t.interrupt();
// Shouldn't be long now
// -- wait indefinitely
//t.join();
}
}
threadMessage("Finally!");
}
}

Where's the time?

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