1) Sleep
package edu.xmu.thread; public class SleepTest { public static void main(String[] args) { Thread thread1 = new Thread(new MyRunnable()); Thread thread2 = new Thread(new MyRunnable()); Thread thread3 = new Thread(new MyRunnable()); System.out.println(System.currentTimeMillis()); thread1.start(); thread2.start(); thread3.start(); System.out.println(System.currentTimeMillis()); } private static class MyRunnable implements Runnable { @Override public void run() { try { System.out.println(Thread.currentThread().getName() + " is going to sleep."); Thread.sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }Output:
1400034838666 Thread-0 is going to sleep. 1400034838666 Thread-1 is going to sleep. Thread-2 is going to sleep. // We can see that static method Thread.sleep() will sleep the current thread.Attention:
System.out.println(System.currentTimeMillis()); thread1.start(); thread2.start(); thread3.start(); thread3.sleep(1000); System.out.println(System.currentTimeMillis()); // Output: //1400035177744 //Thread-0 is going to sleep. //Thread-1 is going to sleep. //Thread-2 is going to sleep. //1400035178744 // The thread3.sleep(1000); will not make thread3 sleep. // It will make current main thread sleep instead. // So we can find out that although threadInstance.sleep() is applicable, // it will make the current thread instead of threadInstance sleep. // Pay attention to this pitfall.
2) Join
Example below:
package edu.xmu.thread; import java.util.ArrayList; import java.util.Arrays; import java.util.Calendar; import java.util.List; public class ThreadTest { public static void main(String[] args) { List<CalculationThread> subThreadList = initSubThreadList(); List<Integer> numList = new ArrayList<Integer>(); for (CalculationThread calThread : subThreadList) { calThread.start(); // Start all calculation thread } try { System.out.println("Current Time Mills: " + Calendar.getInstance().getTimeInMillis()); for (CalculationThread calThread : subThreadList) { calThread.join(); } System.out.println("Current Time Mills: " + Calendar.getInstance().getTimeInMillis()); CalculationThread sumThread = new CalculationThread(); for (CalculationThread subThread : subThreadList) { numList.add(subThread.getSum()); } sumThread.setNumList(numList); sumThread.start(); sumThread.join(); System.out.println("Current Time Mills: " + Calendar.getInstance().getTimeInMillis()); System.out.println(sumThread.getSum()); } catch (InterruptedException e) { e.printStackTrace(); } } private static List<CalculationThread> initSubThreadList() { CalculationThread thread1 = new CalculationThread(Arrays.asList(200, 200, 200, 200)); CalculationThread thread2 = new CalculationThread(Arrays.asList(300, 300, 300, 300)); CalculationThread thread3 = new CalculationThread(Arrays.asList(300, 300, 300, 300)); CalculationThread thread4 = new CalculationThread(Arrays.asList(300, 300, 300, 300)); CalculationThread thread5 = new CalculationThread(Arrays.asList(300, 300, 300, 300)); List<CalculationThread> subThreadList = new ArrayList<CalculationThread>(); subThreadList.add(thread1); subThreadList.add(thread2); subThreadList.add(thread3); subThreadList.add(thread4); subThreadList.add(thread5); return subThreadList; } } class CalculationThread extends Thread { private List<Integer> numList; private int sum; public CalculationThread() { super(); } public CalculationThread(List<Integer> numList) { super(); this.numList = numList; } @Override public void run() { try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } for (int i : numList) { sum += i; } } public int getSum() { return sum; } public void setNumList(List<Integer> numList) { this.numList = numList; } }
Output:
Current Time Mills: 1400033660648 Current Time Mills: 1400033662639 Current Time Mills: 1400033664640 5600 // We can find out the total subCalculation time cost is: 2000ms. // So we can use this kind of technique(join method) to divide // a huge task into several sub-task and start all the sub-task at once // The main thread will wait till all the sub-task done and then gather // all the result together.
Example2: For special requirement that a list of threads run sequentially.
package edu.xmu.thread; public class SequenceThreadTest { public static void main(String[] args) throws InterruptedException { Thread sequenceThread = new Thread(new SequenceThread(), "sequenceThread"); Thread sequenceThread2 = new Thread(new SequenceThread(), "sequenceThread2"); Thread sequenceThread3 = new Thread(new SequenceThread(), "sequenceThread3"); Thread sequenceThread4 = new Thread(new SequenceThread(), "sequenceThread4"); sequenceThread.start(); sequenceThread.join(); // The caller thread(Main thread) will block until sequenceThread finished. sequenceThread2.start(); sequenceThread2.join();// The caller thread(Main thread) will block until sequenceThread2 finished. sequenceThread3.start(); sequenceThread3.join();// The caller thread(Main thread) will block until sequenceThread3 finished. sequenceThread4.start(); sequenceThread4.join();// The caller thread(Main thread) will block until sequenceThread4 finished. System.out.println("Finished"); } } class SequenceThread implements Runnable { @Override public void run() { try { Thread.sleep((long) (1000 * Math.random())); System.out .println("Thread: " + Thread.currentThread() + " is running(). Timestamp: " + System.currentTimeMillis()); } catch (InterruptedException e) { e.printStackTrace(); } } }
Output:
Thread: Thread[sequenceThread,5,main] is running(). Timestamp: 1401247052161 Thread: Thread[sequenceThread2,5,main] is running(). Timestamp: 1401247052625 Thread: Thread[sequenceThread3,5,main] is running(). Timestamp: 1401247053363 Thread: Thread[sequenceThread4,5,main] is running(). Timestamp: 1401247054014 Finished
Another Approach:
package edu.xmu.thread; public class SequenceThreadTest { public static void main(String[] args) throws InterruptedException { Thread sequenceThread = new Thread(new SequenceThread(null), "sequenceThread"); Thread sequenceThread2 = new Thread(new SequenceThread(sequenceThread), "sequenceThread2"); Thread sequenceThread3 = new Thread( new SequenceThread(sequenceThread2), "sequenceThread3"); Thread sequenceThread4 = new Thread( new SequenceThread(sequenceThread3), "sequenceThread4"); sequenceThread.start(); System.out.println("sequenceThread started. Timestamp: " + System.currentTimeMillis()); sequenceThread2.start(); System.out.println("sequenceThread2 started. Timestamp: " + System.currentTimeMillis()); sequenceThread3.start(); System.out.println("sequenceThread3 started. Timestamp: " + System.currentTimeMillis()); sequenceThread4.start(); System.out.println("sequenceThread4 started. Timestamp: " + System.currentTimeMillis()); sequenceThread4.join(); System.out .println("Finished. Timestamp: " + System.currentTimeMillis()); } } class SequenceThread implements Runnable { Thread previousThread; public SequenceThread(Thread previousThread) { super(); this.previousThread = previousThread; } @Override public void run() { try { if (previousThread != null) { previousThread.join(); // The caller thread(current thread) will block until previousThread finished. And main thread will not blocked. } Thread.sleep((long) (1000 * Math.random())); System.out .println("Thread: " + Thread.currentThread() + " is running(). Timestamp: " + System.currentTimeMillis()); } catch (InterruptedException e) { e.printStackTrace(); } } }
Output:
sequenceThread started. Timestamp: 1401247481556 sequenceThread2 started. Timestamp: 1401247481556 sequenceThread3 started. Timestamp: 1401247481556 sequenceThread4 started. Timestamp: 1401247481556 Thread: Thread[sequenceThread,5,main] is running(). Timestamp: 1401247482485 Thread: Thread[sequenceThread2,5,main] is running(). Timestamp: 1401247482935 Thread: Thread[sequenceThread3,5,main] is running(). Timestamp: 1401247483014 Thread: Thread[sequenceThread4,5,main] is running(). Timestamp: 1401247483916 Finished. Timestamp: 1401247483916 // We can see that MainThread will not block.
相关推荐
C++11引入了并发编程的支持,包括`std::future`、`std::promise`以及`std::async`等工具,而`concurrency::task`是微软的PPL(Parallel Patterns Library,并行模式库)的一部分,为C++提供了更高级别的异步编程模型...
《并发的艺术》(The Art of Concurrency: A Thread Monkey's Guide to Writing Parallel Applications)是一本面向程序员的专业书籍,旨在深入讲解并发编程的核心概念和技术。本书由Clay Breshears撰写,并于2009年...
Java Concurrency in Practice 英文无水印pdf pdf所有页面使用FoxitReader和PDF-XChangeViewer测试都可以打开 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请联系上传者...
Basic concepts of concurrency and thread safety Techniques for building and composing thread-safe classes Using the concurrency building blocks in java.util.concurrent Performance optimization dos ...
本教程"JavaConcurrency:Java并发教程"旨在深入探讨Java平台上的并发机制和最佳实践。 Java并发的核心概念包括线程、同步、互斥、死锁以及线程安全。在Java中,线程是并发执行的基本单元,通过创建Thread对象或者...
Java提供了`Thread`类和`Runnable`接口来实现线程,同时讲解了`start()`与`run()`方法的区别。 2. **并发模型**:Java并发模型基于共享内存,其中线程通过内存共享进行通信。书中会讲解监视器(Monitor)、锁(Lock...
Get an easy introduction to reactive streams in Java to handle concurrency, data streams, and the propagation of change in today's applications. This compact book includes in-depth introductions to ...
<<java并行编程>>英文版chm格式,英文名称<Java Concurrency in Practice>,一直想买这本书,但总是缺货,找到了电子版,分享给大家。 Java Concurrency in Practice By Brian Goetz, Tim Peierls, Joshua Bloch,...
Java Concurrency in practice
《Java Concurrency in Practice》是Java并发编程领域的一本经典著作,由Brian Goetz、Tim Peierls、Joshua Bloch、Joseph Bowles和Doug Lea等专家共同编写。这本书深入探讨了Java平台上的多线程和并发编程,旨在...
Java Concurrency in Practice JAVA并发编程实践中文版(全)第二部分
《Java并发编程实践》(Java Concurrency in Practice)是一本深度探讨Java多线程和并发编程的经典著作。这本书由Brian Goetz、Tim Peierls、Joshua Bloch、David Holmes和Doug Lea合著,旨在帮助Java开发者理解和解决...
java concurrency in practice 经典的多线程编程书籍,英文版
在Java中,基础的并发支持包括线程的创建和控制,如`Thread`类和`Runnable`接口。此外,还有同步机制如`synchronized`关键字、`wait()`、`notify()`和`notifyAll()`方法,它们用于确保线程安全,防止数据竞争问题。 ...
本项目"Java-Concurrency:Java并发学习演示"旨在提供一个深入理解Java并发机制的实践平台。以下是对相关知识点的详细说明: 1. **线程与进程**:在计算机系统中,进程是资源分配的基本单位,而线程是执行的基本单位...
java8 源码 并发操作合集 这是一个关于并发的系列。以实战为驱动,了解并发编程中的那些骚操作。文中的示例代码和部分解释来源于网络,你可以把这个系列当做一本工具书,想不起来的时候来看一看,顺便star一发也是...
《Java Concurrency in Practice》是Java并发编程领域的一本经典著作,由Brian Goetz、Tim Peierls、Joshua Bloch、Joe Bowbeer、David Holmes和Doug Lea合著,国内有热心人士进行了中文翻译,使得更多的中国开发者...