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.
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的更多相关文章
- 【转】Java 并发:Executors 和线程池
原文地址: http://baptiste-wicht.com/posts/2010/09/java-concurrency-part-7-executors-and-thread-pools.htm ...
- An Introduction to Lock-Free Programming
Lock-free programming is a challenge, not just because of the complexity of the task itself, but bec ...
- Concurrency Is Not Parallelism (Rob pike)
Rob pike发表过一个有名的演讲<Concurrency is not parallelism>(https://blog.golang.org/concurrency-is-not- ...
- Java 8 Concurrency Tutorial--转
Threads and Executors Welcome to the first part of my Java 8 Concurrency tutorial. This guide teache ...
- 【转】 Anatomy of Channels in Go - Concurrency in Go
原文:https://medium.com/rungo/anatomy-of-channels-in-go-concurrency-in-go-1ec336086adb --------------- ...
- Go Concurrency Patterns: Pipelines and cancellation
https://blog.golang.org/pipelines Go Concurrency Patterns: Pipelines and cancellation Sameer Ajmani1 ...
- Concurrency
<Concurrency>:http://docs.oracle.com/javase/tutorial/essential/concurrency/index.html <Java ...
- Concurrency != Parallelism
前段时间在公司给大家分享GO语言的一些特性,然后讲到了并发概念,大家表示很迷茫,然后分享过程中我拿来了Rob Pike大神的Slides <Concurrency is not Parallel ...
- 利用Python进行数据分析(8) pandas基础: Series和DataFrame的基本操作
一.reindex() 方法:重新索引 针对 Series 重新索引指的是根据index参数重新进行排序. 如果传入的索引值在数据里不存在,则不会报错,而是添加缺失值的新行. 不想用缺失值,可以用 ...
随机推荐
- Orchard官方文档翻译(三) 通过zip文件手动安装Orchard
原文地址:http://docs.orchardproject.net/Documentation/Manually-installing-Orchard-zip-file 想要查看文档目录请用力点击 ...
- 翻译「C++ Rvalue References Explained」C++右值引用详解 Part6:Move语义和编译器优化
本文为第六部分,目录请参阅概述部分:http://www.cnblogs.com/harrywong/p/cpp-rvalue-references-explained-introduction.ht ...
- 在使用 AjaxFileUpload 上传文件时,在项目发布到 iis 后,图片不能预览
在使用 AjaxFileUpload 上传文件时,图片已经上传成功了,在站点没有发布时,可以预览,可是在项目发布到 iis 后,图片就不能预览,在网上找了很多的方案也没解决,最后的解决方案如下: 1 ...
- DownLoadFile - FileHandler
C# 跳转新页面 判断URL文件是不是在于在. C# 指定物理目录下载文件,Response.End导致“正在中止线程”异常的问题 public class FileHandler { public ...
- 洛谷P1113 杂物
P1113 杂务 251通过 441提交 题目提供者该用户不存在 标签图论递推 难度普及/提高- 提交该题 讨论 题解 记录 最新讨论 为什么会只有10分? 题目描述 John的农场在给奶牛挤奶前有很 ...
- js的二元三元操作符
二元 if ( a == b) { alert(a) } // (a == b) && alert(a) if ( a != b) { alert(a) } // (a == b) | ...
- 纯servlet返回xml数据
... void doget..... response.setContentType("application/xml");//设置格式 PrintWriter out = r ...
- javascript ES5 Object对象
原文:http://javascript.ruanyifeng.com/stdlib/object.html 目录 概述 Object对象的方法 Object() Object.keys(),Obje ...
- Android IOS WebRTC 音视频开发总结(四四)-- webrtc图书
本文主要介绍即将出版的webrtc图书相关信息,支持原创,转载必须说明出处,更多详见www.rtc.help --------------------------------------------- ...
- CuteFTP 9.0 上传文件时,中文文件名乱码
解决办法如图: 1.右键--->属性 2.选项---->档案名称编 选择ascⅡ