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参数重新进行排序. 如果传入的索引值在数据里不存在,则不会报错,而是添加缺失值的新行. 不想用缺失值,可以用 ...
随机推荐
- KVM虚拟化(一)—— 介绍与简单使用
一.架构及介绍 KVM(Kernel-based Virtual Machine)它由 Quramnet 开发,该公司于 2008年被 Red Hat 收购: 自Linux 2.6.20后整合到内核, ...
- http协议状态码对照表
1**:请求收到,继续处理 2**:操作成功收到,分析.接受 3**:完成此请求必须进一步处理 4**:请求包含一个错误语法或不能完成 5**:服务器执行一个完全有效请求失败 100——客户必须继续发 ...
- 智能指针(一):STL auto_ptr实现原理
智能指针实际上是一个类(class),里面封装了一个指针.它的用处是啥呢? 指针与内存 说到指针自然涉及到内存.我们如果是在堆栈(stack)中分配了内存,用完后由系统去负责释放.如果是自定义类型,就 ...
- Use EnCase to acquire data from a smartphone
Yesterday someone asked me a question can EnCase acquire data from a smartphone, and my reply was &q ...
- JAVA设计模式--State(状态模式)
状态模式(State Pattern)是设计模式的一种,属于行为模式. 定义(源于Design Pattern):当一个对象的内在状态改变时允许改变其行为,这个对象看起来像是改变了其类. 状态模式主要 ...
- Android IOS WebRTC 音视频开发总结(十八)-- 手机适配
本文主要介绍上次碰到的某些机器上看不到视频的问题,文章来自博客园RTC.Blacker,转载请说明出处. 之前做的视频聊天App一直运行良好,前几天客户反馈说在三星9100. Android4.0.3 ...
- 条款19 command 模式与好莱坞法则
当一个函数对象被当做回调时候,就是一个command模式的实例 什么是回调? 回调就是框架知道什么时候干一些事情,但是具体干什么,或许框架一无所知(因为回调函数不是他设计的),而用户则知道发生一个特定 ...
- Valid Parentheses [LeetCode 20]
1- 问题描述 Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if ...
- GUI_DOWNLOAD参数说明
对FUNCTION: GUI_DOWNLOAD中某些参数的用法. call function 'GUI_DOWNLOAD' exporting * BIN_FILESIZE ...
- ASP.NET数据控件
数据服务器控件就是能够显示数据的控件,与那些简单格式的列表控件不同,这些控件不但提供显示数据的丰富界面(可以显示多行多列数据并根据用户定义来显示),还提供了修改.删除和插入数据的接口. ASP.NET ...