Java中的并发线程操作(只贴代码,内有注释)
package com.thread1; public class LiffOff implements Runnable{ protected int countDown = 10;
private static int taskCount = 0;
private final int id = taskCount++; public LiffOff() {
} public LiffOff(int countDown) {
this.countDown = countDown;
} public String status(){
return "#" + id + "("+(countDown > 0? countDown:"Liftoff!")+").";
} @Override
public void run() {
while(countDown-- > 0){
System.out.println(status());
Thread.yield();
}
} }
package com.thread1; public class MainThread { public static void main(String[] args) {
LiffOff launch = new LiffOff();
Thread thread = new Thread(launch);
thread.start();
}
}
2.使用Executors.newCachedThreadPool
调用线程
package com.thread1; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class CachedThreadPool { public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
for(int i=0;i<5;i++){
exec.execute(new LiffOff());
}
exec.shutdown();
}
}
3.使用Executors.newFixedThreadPool
package com.thread1; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class FixedThreadPool { public static void main(String[] args) {
ExecutorService exec = Executors.newFixedThreadPool(5);
for(int i=0;i<5;i++){
exec.execute(new LiffOff());
}
exec.shutdown();
}
}
4.带返回值的线程,实现callable
package com.thread1; import java.util.concurrent.Callable; public class TaskWithResult implements Callable<String>{ private int id; public TaskWithResult(int id) {
this.id = id;
} @Override
public String call() throws Exception { return " result of TaskWithResult "+id;
} }
package com.thread1; import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future; public class CallDemo { public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
ArrayList<Future<String>> results = new ArrayList<Future<String>>(); for(int i=0;i<10;i++){
//submit方法会产生future对象,使用isDone()来查询future是否完成
results.add(exec.submit(new TaskWithResult(i)));
}
for(Future<String> fs : results){
try {
System.out.println(fs.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}finally {
exec.shutdown();
}
}
}
}
5.线程的睡眠
package com.thread1; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; public class SleeptingTask extends LiffOff{ public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
for(int i=0;i<5;i++){
exec.execute(new SleeptingTask());
}
exec.shutdown();
} @Override
public void run() {
while(countDown-- >0){
System.out.println(status());
try {
TimeUnit.MILLISECONDS.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("interrupted");
}
}
} }
6.线程的优先级
.yield()暗示其他线程可以运行
package com.thread1; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; /**
* 通过 getPriority setPriority获取设置线程的优先级
* @author admin
*
*/
public class SimplePriorities implements Runnable{ private int countDown = 5;
private volatile double d;
private int priority; public SimplePriorities(int priority) {
this.priority = priority;
} @Override
public String toString() {
return Thread.currentThread()+" : "+countDown;
}
@Override
public void run() {
Thread.currentThread().setPriority(priority);
while(true){
for(int i=1;i>10000;i++){
d += (Math.PI+Math.E)/(double)i;
if(i%1000 == 0){
Thread.yield();
}
System.out.println(this);
if(--countDown == 0) return;
}
}
} public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
for(int i=1;i>5;i++)
exec.execute(new SimplePriorities(Thread.MAX_PRIORITY));
exec.execute(new SimplePriorities(Thread.MIN_PRIORITY));
exec.shutdown();
} }
7.线程的加入-join(),也可在join()方法带上一个超时参数,如果目标线程在此期间还没有结束,join()总能返回.
package com.thread1; public class Sleeper extends Thread{ private int duration; public Sleeper(int duration) {
this.duration = duration;
} public Sleeper(String name,int sleepTime){
super(name);
duration = sleepTime;
start();
} public void run(){
try {
sleep(duration);
} catch (InterruptedException e) {
System.out.println(getName()+"was interrupted. isInterrupted():"+isInterrupted());
return;
}
System.out.println(getName()+" has awakened");
}
}
package com.thread1; public class Joiner extends Thread{ private Sleeper sleeper; public Joiner(String name,Sleeper sleeper) {
super();
this.sleeper = sleeper;
start();
} public void run(){
try {
sleeper.join();
} catch (Exception e) {
System.out.println("interrupted");
}
System.out.println(getName()+ " join completed");
} }
package com.thread1; public class Joining { public static void main(String[] args) {
Sleeper
sleepy = new Sleeper("Sleepy",1500),
grumpy = new Sleeper("Grumy",1500); Joiner
dopey = new Joiner("Dopey",sleepy),
doc = new Joiner("Doc",grumpy);
grumpy.interrupt();
}
}
执行结果:
8.线程中的异常捕获
1:制造异常
package com.thread1; import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class ExceptionThread implements Runnable{ @Override
public void run() {
throw new RuntimeException();
} public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
exec.execute(new ExceptionThread());
}
}
输出如下:
Java中的并发线程操作(只贴代码,内有注释)的更多相关文章
- Java中如何创建线程
Java中如何创建线程 两种方式:1)继承Thread类:2)实现Runnable接口. 1.继承Thread类 继承Thread类,重写run方法,在run方法中定义需要执行的任务. class M ...
- Java中的守护线程 & 非守护线程(简介)
Java中的守护线程 & 非守护线程 守护线程 (Daemon Thread) 非守护线程,又称用户线程(User Thread) 用个比较通俗的比如,任何一个守护线程都是整个JVM中所有非守 ...
- JAVA中的集合容器操作类
目录 JAVA中的集合容器操作类 List集合 ArrayList的操作方法说明 LinkedList Stack Set Map Queue 总结 JAVA中的集合容器操作类 Java容器类库总共分 ...
- Java 中的并发工具类
Java 中的并发工具类 CountDownLatch public class JoinCountDownLatchTest { public static void main(String[] a ...
- Java中传入一个时间范围,取出该时间范围内所有日期的集合
直接上代码: import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; impor ...
- JAVA中关于并发的一些理解
一,JAVA线程是如何实现的? 同步,涉及到多线程操作,那在JAVA中线程是如何实现的呢? 操作系统中讲到,线程的实现(线程模型)主要有三种方式: ①使用内核线程实现 ②使用用户线程实现 ③使用用户线 ...
- java编程思想-java中的并发(二)
二.共享受限资源 有了并发就可以同时做多件事情了.但是,两个或多个线程彼此互相干涉的问题也就出现了.如果不防范这种冲突,就可能发生两个线程同时试图访问同一个银行账户,或向同一个打印机打印,改变同一个值 ...
- java编程思想-java中的并发(一)
一.基本的线程机制 并发编程使我们可以将程序划分为多个分离的.独立运行的任务.通过使用多线程机制,这些独立任务中的每一个都将由执行线程来驱动. 线程模型为编程带来了便利,它简化了在单一程序中同时jia ...
- Java中的并发编程集合使用
一.熟悉Java自带的并发编程集合 在java.util.concurrent包里有很多并发编程的常用工具类. package com.ietree.basicskill.mutilthread.co ...
随机推荐
- 解析const
const在函数前与函数后的区别 一 const基础 如果const关键字不涉及到指针,我们很好理解,下面是涉及到指针的情况: int b = 500; ...
- JS实现一个简单的计算器
使用JS完成一个简单的计算器功能.实现2个输入框中输入整数后,点击第三个输入框能给出2个整数的加减乘除.效果如上: 第一步: 创建构建运算函数count(). 第二步: 获取两个输入框中的值和获取选择 ...
- VMware网络配置 - 三种网络模式简介
安装好虚拟机以后,在网络连接里面可以看到多了两块网卡: 其 中VMnet1是虚拟机Host-only模式的网络接口,VMnet8是NAT模式的网络接口,这些后面会详细介绍 选择虚拟机网络模 式方法如下 ...
- magento email模板设置相关
magento后台 可以设置各种各样的邮件,当客户注册.下单.修改密码.邀请好友等等一系列行为时,会有相关信息邮件发出. 进入magento后台,System > Transactional E ...
- 获取设备的唯一标识uuid
摘自:http://blog.sina.com.cn/s/blog_5971cdd00102vqgy.html -(NSString*) uuid { CFUUIDRef puuid = CFUUID ...
- Selenium2学习-037-WebUI自动化实战实例-IE浏览器显示比例问题:org.openqa.selenium.remote.SessionNotFoundException: Unexpected error launching Internet Explorer. Browser zoom level was set to 94%. It should be set to 100%
好久没有写博文了,今天在给部门新人演示 Selenium WebDriver 启动其支持的各种浏览器时,启动 IE 时总是无法打开对应的百度网址,页面如下所示:
- TestNG学习-002-annotaton 注解概述及其执行顺序
此文主要讲述用 TestNG 基础的 annotation (注解)知识,及其执行的顺序,并通过一个 TestNG 简单的实例演示 annotation 的执行顺序. 希望能对初学 TestNG 测试 ...
- asp.net MVC中如何用Membership类和自定义的数据库进行登录验证
asp.net MVC 内置的membershipProvider可以实现用户登陆验证,但是它用的是自动创建的数据库,所以你想用本地数据库数据去验证,是通过不了的. 如果我们想用自己的数据库的话,可以 ...
- SQL Server 未保存.sql文件,还想查看、修改一些建表语句、存储过程等怎么办?
SP_HELPTEXT 表名/视图名/存储过程名:
- Exception not a valid month
oracle中的to_date('date','pattern') 其中的date和pattern格式应该要一样 SELECT to_date('2016-03-29 00:00:00','yyyy- ...