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?

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

Concurrency Series 1的更多相关文章

  1. 【转】Java 并发:Executors 和线程池

    原文地址: http://baptiste-wicht.com/posts/2010/09/java-concurrency-part-7-executors-and-thread-pools.htm ...

  2. An Introduction to Lock-Free Programming

    Lock-free programming is a challenge, not just because of the complexity of the task itself, but bec ...

  3. Concurrency Is Not Parallelism (Rob pike)

    Rob pike发表过一个有名的演讲<Concurrency is not parallelism>(https://blog.golang.org/concurrency-is-not- ...

  4. Java 8 Concurrency Tutorial--转

    Threads and Executors Welcome to the first part of my Java 8 Concurrency tutorial. This guide teache ...

  5. 【转】 Anatomy of Channels in Go - Concurrency in Go

    原文:https://medium.com/rungo/anatomy-of-channels-in-go-concurrency-in-go-1ec336086adb --------------- ...

  6. Go Concurrency Patterns: Pipelines and cancellation

    https://blog.golang.org/pipelines Go Concurrency Patterns: Pipelines and cancellation Sameer Ajmani1 ...

  7. Concurrency

    <Concurrency>:http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html <Java ...

  8. Concurrency != Parallelism

    前段时间在公司给大家分享GO语言的一些特性,然后讲到了并发概念,大家表示很迷茫,然后分享过程中我拿来了Rob Pike大神的Slides <Concurrency is not Parallel ...

  9. 利用Python进行数据分析(8) pandas基础: Series和DataFrame的基本操作

    一.reindex() 方法:重新索引 针对 Series   重新索引指的是根据index参数重新进行排序. 如果传入的索引值在数据里不存在,则不会报错,而是添加缺失值的新行. 不想用缺失值,可以用 ...

随机推荐

  1. http 302

    404 not found500 internal server error 302临时重定向.指被访问的网页由于各种需求临时跳转到其它页面. yii若用户为游客状态,但controller中添加了权 ...

  2. 学习总结 html 表格标签的使用

    表格: <table></table>表格 width:宽度.可以用像素或百分比表示. 常用960像素. border:边框,常用值为0. cellpadding:内容跟边框的 ...

  3. mysql下的常用操作

    本文继 linux下安装mysql,记录下在工作中最常用的mysql语句 MySQL添加字段和删除字段 添加字段: alter table `user_movement_log`Add column ...

  4. android style 中一些颜色的定义

    colorControlNormal 单选多选等控件颜色 colorControlActivated 单选多选等控件激活颜色

  5. PAT1023. Have Fun with Numbers

    //水题,但是考点不水,可能用的strlen属于string库,但是只能用于字符,不能用数字,因为\0就是0.出现0无法判断,其次二倍时有可能有进位 //第一次在二倍进位上出了问题 #include& ...

  6. [转]回答--python django学的很迷茫怎么办?

    作者:王一链接:http://www.zhihu.com/question/26235428/answer/36568428来源:知乎著作权归作者所有.商业转载请联系作者获得授权,非商业转载请注明出处 ...

  7. PHP获取今天、昨天、明天的日期

    <?php echo "今天:".date("Y-m-d")."<br>"; echo "昨天:".d ...

  8. 【Linux】Zabbix自定义触发器语法

    Zabbix触发器的语法如下: {<server>:<key>.<function>(<parameter>)}<operator>< ...

  9. C# 事务处理

    前言: 通常SqlHelper类为了方便处理,做成了静态类,静态类的问题是不方便添加事务处理. 实例化类方便添加事务处理,DoTrans/CommitTrans/RollBackTrans  三个函数 ...

  10. 在centos下安装django

    这里有一个不错的Django的学习资料.先收藏一下,以备后用.谢谢 http://www.ziqiangxuetang.com/django/django-install.html 在centos下安 ...