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参数重新进行排序. 如果传入的索引值在数据里不存在,则不会报错,而是添加缺失值的新行. 不想用缺失值,可以用 ...
随机推荐
- Ubuntu14.04 caffe 配置
1.前置条件验证 (1) Ubuntu14.04操作系统. (2) 检验计算机是否为NVIDIA显卡,终端输入命令 $ lspci | grep -invidia (3) 检验计算机是否为x86_6 ...
- js获取服务器控件DropDownList所选中的各项属性
var ddl = document.getElementById("DropDownList1"); alert(ddl.selectedIndex);//选择索引值 alert ...
- Oracle 删表前验证表名是否存在并且删除
DECLARE num NUMBER; BEGIN SELECT COUNT(1) INTO num FROM USER_TABLES WHERE TABLE_NAME = UPPER('tableN ...
- FindResource函数错误代码:1813-找不到映像文件中指定的资源类型 与LoadResource函数错误代码:1812-指定的映像文件不包含资源区域
HRSRC WINAPI FindResource( _In_opt_ HMODULE hModule, _In_ LPCTSTR lpName, _In_ LPCTSTR lp ...
- oracle 将查询到的数据插入表
1. 新增一个表,通过另一个表的结构和数据 create table tab1 as select * from tab2 2. 如果表存在: insert into tab1 select * fr ...
- 集群监控系统Ganglia应用案例
集群监控系统Ganglia应用案例 --我们把集群系统投入生产环境后,这时就需要一套可视化的工具来监视集群系统,这将有助于我们迅速地了解机群的整体配置情况,准确地把握机群各个监控节点的信息,全面地察看 ...
- 【Hibernate 4】一对多映射配置
一.一对多映射简介 建立一对多关系关系的表的原则是将一的一方的主键加入到多的一方的表作为外键.这里以学生和班级为例子来演示.以前不用hibernate时建立pojo类要在学生类Student中加入一个 ...
- 详解H264视频格式-2016.01.28
专业名词解释 VCL(Video Coding Layer)视频编码层 NAL(Network Abstraction Layer)网络提取层 SPS(Sequence Parameter Set) ...
- css透明属性
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...
- C# 加密算法
public static class Common { #region MD5加密 /// <summary> /// M ...