轻松学习多线程 01-多线程入门基础知识
Thread
In concurrent programming, there are two basic units of execution: processes and threads.
A process has a self-contained execution environment. 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.

Thread Objects
Each thread is associated with an instance of the class Thread.
Define and Start a Thread
- Provide a Runnable object. The Runnable interface defines a single method, run, meant to contain the code executed in the thread.
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();
}
}
- Subclass Thread. The Thread class itself implements Runnable, though its run method does nothing.
public class HelloThread extends Thread {
public void run() {
System.out.println("Hello from a thread!");
}
public static void main(String args[]) {
(new HelloThread()).start();
}
}
Pausing Execution
Thread.sleep() causes the current thread to suspend execution for a specified period.
public class SleepMessage {
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 Simple thread demo
```java
public class SimpleThread {
// 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 (String anImportantInfo : importantInfo) {
// Pause for 2 seconds
Thread.sleep(2000);
// Print a message
threadMessage(anImportantInfo);
}
} catch (InterruptedException e) {
threadMessage("I wasn't done!");
}
}
}
public static void main(String args[])
throws InterruptedException {
// Delay, in milliseconds before
// we interrupt MessageLoop
// thread (default 1 minute).
final long PATIENCE = 1000 * 60;
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!");
}
}
result
main: Starting MessageLoop thread
main: Waiting for MessageLoop thread to finish
main: Still waiting...
main: Still waiting...
Thread-0: Mares eat oats
main: Still waiting...
main: Still waiting...
Thread-0: Does eat oats
main: Still waiting...
main: Still waiting...
Thread-0: Little lambs eat ivy
main: Still waiting...
main: Still waiting...
Thread-0: A kid will eat ivy too
main: Finally!
Process finished with exit code 0
- Now, let's we change the PATIENCE of main thread wait to one second.
result
main: Starting MessageLoop thread
main: Waiting for MessageLoop thread to finish
main: Still waiting...
main: Tired of waiting!
Thread-0: I wasn't done!
main: Finally!
Process finished with exit code 0
Synchronization
Threads communicate primarily by sharing access to fields and the objects reference fields refer to.
This form of communication is extremely efficient, but makes two kinds of errors possible: thread interference and memory consistency errors.
However, synchronization
can introduce thread contention, which occurs when two or more threads try to access the same resource simultaneously
and cause the Java runtime to execute one or more threads more slowly, or even suspend their execution.
Memory Consistency Errors
Memory consistency errors occur when different threads have inconsistent views of what should be the same data.
The causes of memory consistency errors are complex and beyond the scope of this tutorial. Fortunately, the programmer does not need a detailed understanding of these causes.
- Counter.java
public class Counter {
private int value = 0;
public void increment() {
value += 10;
}
@Override
public String toString() {
return "Counter{" +
"value=" + value +
'}';
}
}
- CounterRunnable.java
public class CounterRunnable implements Runnable {
private Counter counter = new Counter();
@Override
public void run() {
for(int i = 0; i [Java实现定时任务的三种方法](http://www.360doc.com/content/14/0410/08/7823806_367676309.shtml)
> [使用java自带的定时任务ScheduledThreadPoolExecutor](http://www.cnblogs.com/yaoyuan23/p/5584058.html)
TBC...
> [多线程实战](http://ifeve.com/java-active-object/)
# Thread pool
> [Java线程池的分析和使用](http://ifeve.com/java-threadpool/)
一、线程池的必要
- 降低资源消耗。
通过重复利用已创建的线程降低线程创建和销毁造成的消耗。
- 提高响应速度。
当任务到达时,任务可以不需要的等到线程创建就能立即执行。
- 提高线程的可管理性。
线程是稀缺资源,如果无限制的创建,不仅会消耗系统资源,还会降低系统的稳定性,使用线程池可以进行统一的分配,调优和监控。