java多线程的使用1
方式1:
public class LiftOff implements Runnable {
protected int countDown = ;
private static int taskCount = ;
private final int id = taskCount++; public LiftOff() {
System.out.println("LiftOff Start:"+Thread.currentThread().getId());
} public LiftOff(int countDown) {
this.countDown = countDown;
} public String status() {
System.out.println("LiftOff tid:"+Thread.currentThread().getId());
return "#" + id + "(" + (countDown > ? countDown : "Liftoff!") + "),";
} public void run() { while (countDown-- > ) {
// System.out.print();
status();
//Thread.yield();
}
System.out.println("LiftOff End:"+Thread.currentThread().getId());
} }
public class BasicThreads { public static void main(String[] args){
System.out.println("main tid:"+Thread.currentThread().getId());
Thread t=new Thread(new LiftOff());
t.start();
System.out.println("Waiting for LiftOff");
}
}
方式2(首选):
不限制数量的线程池
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 = ; i < ; i++) {
exec.execute(new LiftOff());
}
exec.shutdown();
}
}
方式3:
限制数量的线程池
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class FixedThreadPool {
public static void main(String[] args) {
ExecutorService exec=Executors.newFixedThreadPool();
for (int i = ; i < ; i++) {
exec.execute(new LiftOff());
}
exec.shutdown();
}
}
方式4:
线程顺序执行
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors; public class SingleThreadExecutor {
public static void main(String[] args) {
ExecutorService exec = Executors.newSingleThreadExecutor();
for (int i = ; i < ; i++) {
exec.execute(new LiftOff());
}
exec.shutdown();
}
}
方式5:
调用线程并返回结果
import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future; class TaskWithResult implements Callable<String> {
private int id; public TaskWithResult(int id) {
this.id = id;
} public String call() {
return "result of TaskWithResult " + id;
}
} public class CallableDemo {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService exec = Executors.newCachedThreadPool();
System.out.println(exec.submit(new TaskWithResult(50)).get());
ArrayList<Future<String>> results = new ArrayList<Future<String>>();
for (int i = 0; i < 10; i++) {
results.add(exec.submit(new TaskWithResult(i)));
}
for (Future<String> fs : results) {
try {
System.out.println(fs.get());
} catch (InterruptedException e) {
System.out.println(e);
return;
} catch (ExecutionException e) {
System.out.println(e);
} finally {
exec.shutdown();
}
}
} }
方式6:
后台线程,当主线程退出时(非后台线程),后台线程也自动退出
import java.util.concurrent.TimeUnit; public class SimpleDaemons implements Runnable{ public void run() {
try {
while (true) {
TimeUnit.MICROSECONDS.sleep(100);
System.out.println(Thread.currentThread()+" "+this);
//print(Thread.currentThread()+" "+this);
}
} catch (Exception e) {
e.printStackTrace();
}
} public static void main(String[] args) throws InterruptedException {
// for (int i = 0; i < 10; i++) {
Thread daemon=new Thread(new SimpleDaemons());
daemon.setDaemon(true);
daemon.start();
// }
System.out.println("All daemons started");
TimeUnit.MICROSECONDS.sleep(175);
System.out.println("All daemons end");
}
}
方式7:
后台线程的第二种写法
import java.util.concurrent.ThreadFactory; public class DaemonThreadFactory implements ThreadFactory{ @Override
public Thread newThread(Runnable r) {
Thread t=new Thread(r);
t.setDaemon(true);
return t;
} }
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit; public class DaemonFromFactory implements Runnable{
public void run() {
try {
while (true) {
TimeUnit.MICROSECONDS.sleep(100);
System.out.println(Thread.currentThread()+" "+this);
}
} catch (Exception e) {
System.out.println("Interrupted");
}
} public static void main(String[] args) throws InterruptedException {
ExecutorService exec=Executors.newCachedThreadPool(new DaemonThreadFactory());
for (int i = 0; i < 10; i++) {
exec.execute(new DaemonFromFactory());
}
System.out.println("All daemons started");
TimeUnit.MILLISECONDS.sleep(500);
}
}
方式8:
通过继承Thread类
public class SimpleThread extends Thread { private int countDown = 5;
private static int threadCount = 0; public SimpleThread() {
super(Integer.toString(++threadCount));
start();
} public String toString() {
return "#" + getName() + "(" + countDown + "),";
} public void run() {
while (true) {
System.out.println(this);
if(--countDown==0)
return;
}
}
public static void main(String[] args) {
for (int i = 0; i < 5; i++) {
new SimpleThread();
}
}
}
方式9:
匿名内部类
import java.util.concurrent.TimeUnit; class InnerThread1 {
private int countDown = 5;
private Inner inner; private class Inner extends Thread {
Inner(String name) {
super(name);
start();
} public void run() {
try {
while (true) {
System.out.println(this);
if (--countDown == 0)
return;
sleep(10);
}
} catch (Exception e) {
System.out.println("interrupted");
}
} public String toString() {
return getName() + ":" + countDown;
}
} public InnerThread1(String name) {
inner = new Inner(name);
}
} class InnerThread2 {
private int countDown = 5;
private Thread t; public InnerThread2(String name) {
t = new Thread(name) {
public void run() {
try {
while (true) {
System.out.println(this);
if (--countDown == 0)
return;
sleep(10);
}
} catch (Exception e) {
System.out.println("sleep() interrupted");
}
}
};
t.start();
}
} class InnerRunnable1 {
private int countDown = 5;
private Inner inner; private class Inner implements Runnable {
Thread t; Inner(String name) {
t = new Thread(this, name);
t.start();
} public void run() {
try {
while (true) {
System.out.println(this);
if (--countDown == 0)
return;
TimeUnit.MILLISECONDS.sleep(10);
}
} catch (Exception e) {
System.out.println("sleep() interrupted");
}
} public String toString() {
return t.getName() + ":" + countDown;
}
} public InnerRunnable1(String name) {
inner = new Inner(name);
}
} class InnerRunnable2 {
private int countDown = 5;
private Thread t; public InnerRunnable2(String name) {
t = new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
System.out.println(this);
if (--countDown == 0)
return;
TimeUnit.MICROSECONDS.sleep(10);
}
} catch (Exception e) {
System.out.println("sleep() interrupted");
}
} public String toString() {
return Thread.currentThread().getName() + ":" + countDown;
}
}, name);
t.start();
}
} class ThreadMethod {
private int countDown = 5;
private Thread t;
private String name; public ThreadMethod(String name) {
this.name = name;
} public void runTask() {
if (t == null) {
t = new Thread(name) {
public void run() {
try {
while (true) {
System.out.println(this);
if (--countDown == 0)
return;
sleep(10);
}
} catch (Exception e) {
System.out.println("sleep() interrupted");
}
} public String toString() {
return getName() + ":" + countDown;
}
};
t.start();
}
}
} public class ThreadVariations {
public static void main(String[] args) {
new InnerThread1("InnerThread1");
new InnerThread2("InnerThread2");
new InnerRunnable1("InnerRunnable1");
new InnerRunnable2("InnerRunnable2");
new ThreadMethod("ThreadMethod").runTask();
}
}
java多线程的使用1的更多相关文章
- 40个Java多线程问题总结
前言 Java多线程分类中写了21篇多线程的文章,21篇文章的内容很多,个人认为,学习,内容越多.越杂的知识,越需要进行深刻的总结,这样才能记忆深刻,将知识变成自己的.这篇文章主要是对多线程的问题进行 ...
- Java多线程基础知识篇
这篇是Java多线程基本用法的一个总结. 本篇文章会从一下几个方面来说明Java多线程的基本用法: 如何使用多线程 如何得到多线程的一些信息 如何停止线程 如何暂停线程 线程的一些其他用法 所有的代码 ...
- Java多线程系列--“JUC锁”03之 公平锁(一)
概要 本章对“公平锁”的获取锁机制进行介绍(本文的公平锁指的是互斥锁的公平锁),内容包括:基本概念ReentrantLock数据结构参考代码获取公平锁(基于JDK1.7.0_40)一. tryAcqu ...
- Java多线程系列--“JUC锁”04之 公平锁(二)
概要 前面一章,我们学习了“公平锁”获取锁的详细流程:这里,我们再来看看“公平锁”释放锁的过程.内容包括:参考代码释放公平锁(基于JDK1.7.0_40) “公平锁”的获取过程请参考“Java多线程系 ...
- Java多线程--让主线程等待子线程执行完毕
使用Java多线程编程时经常遇到主线程需要等待子线程执行完成以后才能继续执行,那么接下来介绍一种简单的方式使主线程等待. java.util.concurrent.CountDownLatch 使用c ...
- Java多线程 2 线程的生命周期和状态控制
一.线程的生命周期 线程状态转换图: 1.新建状态 用new关键字和Thread类或其子类建立一个线程对象后,该线程对象就处于新生状态.处于新生状态的线程有自己的内存空间,通过调用start方法进入就 ...
- java 多线程 1 线程 进程
Java多线程(一).多线程的基本概念和使用 2012-09-10 16:06 5108人阅读 评论(0) 收藏 举报 分类: javaSE综合知识点(14) 版权声明:本文为博主原创文章,未经博 ...
- 一起阅读《Java多线程编程核心技术》
目录 第一章 Java多线程技能 (待续...)
- 第一章 Java多线程技能
1.初步了解"进程"."线程"."多线程" 说到多线程,大多都会联系到"进程"和"线程".那么这两者 ...
- java从基础知识(十)java多线程(下)
首先介绍可见性.原子性.有序性.重排序这几个概念 原子性:即一个操作或多个操作要么全部执行并且执行的过程不会被任何因素打断,要么都不执行. 可见性:一个线程对共享变量值的修改,能够及时地被其它线程看到 ...
随机推荐
- GPU(CUDA)学习日记(十一)------ 深入理解CUDA线程层次以及关于设置线程数的思考
GPU线程以网格(grid)的方式组织,而每个网格中又包含若干个线程块,在G80/GT200系列中,每一个线程块最多可包含512个线程,Fermi架构中每个线程块支持高达1536个线程.同一线程块中的 ...
- CentOS 6 下RPM方式安装MySQL5.6
CentOS 6 下RPM方式安装MySQL5.6 1. 下载Linux对应的RPM包,如:CentOS6.7_64对应的RPM包,如下:[root@mysql ~]# ll总用量 113808-rw ...
- 异构平台同步(Mysql到Oracle)
Oracle GoldenGate学习之--异构平台同步(MySQL到Oracle) 如图所示:源端采用Mysql库,目标端采用Oracle库 一.OGG安装配置(源端) 1.OGG下载 https: ...
- Unity3d 适配机型
1,为了是更多机型能够安装你的游戏,Unity3d Device Filter设置:ARMv6 with VFP: 2,华为C8600,一运行强制停止: 参考网址:http://forum.unity ...
- MySQL – optimizer_search_depth
Working on customer case today I ran into interesting problem – query joining about 20 tables (thank ...
- redis模块
http://www.cnblogs.com/melonjiang/p/5342505.html http://www.django-china.cn/topic/1054/ 1.连接方式 redis ...
- node.js BootStrap安装
最近想用Bootstrap开发项目,以便使用其丰富的资源: 捯饬了一下nodejs的安装和配置:windows下弄起来还是比较狗屎的,两三天下班时间才弄好: http://xiaoyaojones.b ...
- 运行setup.js文件
C:\Windows\System32>wscript.exe setup.js
- JAVA获取时间戳,哪个更快
目前获取毫秒值大概有下面三种方法 //方法 一 System.currentTimeMillis(); //方法 二 Calendar.getInstance().getTimeInMillis(); ...
- selenium+python自动化之pycharm
方法: 1.注册机界面,选择License serve.填入http://www.cnblogs.com/testdream/ 2.点击ok 3.注册界面选择:Activation coede 4.打 ...