Java 创建线程的方法
为了偷懒少敲几个字这里我写了一个Util类:
package test;
public class Util {
static void println() {System.out.println();}
static void println(Object obj) {System.out.println(obj);}
}
并且在之后的代码中都加入了:
package test;
import static test.Util.*;
1.实现Runnable接口
class simpleRunnable implements Runnable {
private int n = 3;
private static int count = 0;
protected final int id = count++;
public simpleRunnable() {
println("#" + id +" start");
}
@Override
public void run() {
while(n-->0){
println("#" +id +":" + n);
Thread.yield();
}
println("#" + id +" end");
}
}
public class test {
public static void main(String[] args) {
new Thread(new simpleRunnable()).start();
}
}
还有一种自管理的Runnable:
class simpleRunnable2 implements Runnable {
private Thread t = new Thread(this);
private int n = 3;
private static int count = 0;
private final int id = count++;
public simpleRunnable2() {t.start();}
@Override
public void run() {
while(n-->0){
println("#" +id +":" + n);
Thread.yield();
}
println("#" + id +" end");
}
}
public class test {
public static void main(String[] args) {
new simpleRunnable2();
}
}
2.继承Thread类
class simpleThread extends Thread{
private int n = 3;
private static int count = 0;
private final int id = count++;
public simpleThread() {
println("#" + id +" start");
}
public void run() {
while(n-->0){
println("#" +id +":" + n);
Thread.yield();
}
println("#" + id +" end");
}
}
public class test {
public static void main(String[] args) {
new simpleThread().start();
}
}
3.内部类
3.1实现Runnable接口的内部类
class innerRunnable{
private static int count = 0;
private Inner inner;
private class Inner implements Runnable {
private int n = 3;
private final int id = count++;
Thread t = new Thread(this);
public Inner() {t.start();}
@Override
public void run() {
while(n-->0){
println("#" +id +":" + n);
Thread.yield();
}
println("#" + id +" end");
}
}
public innerRunnable() {
inner = new Inner();
}
}
class innerRunnable2{
private static int count = 0;
private Thread t;
public innerRunnable2() {
t = new Thread(new Runnable(){
//实现Runnable接口的匿名内部类
private int n = 3;
private final int id = count++;
@Override
public void run() {
while(n-->0){
println("ir2#" +id +":" + n);
Thread.yield();
}
println("ir2#" + id +" end");
}
});
t.start();
}
}
public class test {
public static void main(String[] args) {
new innerRunnable();
new innerRunnable2();
}
}
3.2继承Thread类的内部类
class innerThread {
private static int count = 0;
private Inner inner;
private class Inner extends Thread {
private int n = 3;
private final int id = count++;
public Inner(){
super();
start();
}
public void run() {
while(n-->0){
println("#" +id +":" + n);
Thread.yield();
}
println("#" + id +" end");
}
}
public innerThread(){
inner = new Inner();
}
}
public class test {
public static void main(String[] args) {
new innerThread();
}
}
当然同样可以用匿名匿名内部类,和Runnable是类似的,就不放上来了。
3.3在方法中使用匿名内部类
class ThreadMethod {
private static int count = 0;
private Thread t;
public void runTask() {
if(t == null) {
t = new Thread(new Runnable(){
private int n = 3;
private final int id = count++;
@Override
public void run() {
while(n-->0){
println("ir2#" +id +":" + n);
Thread.yield();
}
println("ir2#" + id +" end");
}
});
t.start();
}
}
}
public class test {
public static void main(String[] args) {
new innerThread();
}
}
4.使用Executor
首先import一些用的到的包:
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
4.1CachedThreadPool
public class test {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
for(int i = 0; i < 5; i++)
exec.execute(new simpleRunnable());
exec.shutdown();
}
}
CachedThreadPool为每个任务创建一个线程。
4.2FixedThreadPool
public class test {
public static void main(String[] args) {
ExecutorService exec = Executors.newFixedThreadPool(3);
for(int i = 0; i < 5; i++)
exec.execute(new simpleRunnable());
exec.shutdown();
}
}
newFixedThreadPool()需要一个整型参数,记为n,并当参数n <=0 时抛出IllegalArgumentException;这个方法会一次行创建n个线程,并且在这n个线程都在有任务时将后来的线程加入一个队列中,所有的任务都被new并且被接收。
4.3SingleThreadExecutor
public class test {
public static void main(String[] args) {
ExecutorService exec = Executors.newSingleThreadExecutor();
for(int i = 0; i < 5; i++)
exec.execute(new simpleRunnable());
exec.execute(new simpleRunnable());
exec.shutdown();
}
}
SingleThreadExecutor就相当于线程数为1的FixedThreadPool。
4.4实现Callable接口
class simpleCallable implements Callable<Integer>{
@Override
public Integer call() throws Exception {
return (int)(Math.random() * 10 + 1);
}
}
public class test {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool();
List<Future<Integer>> list = new ArrayList();
for(int i = 0; i < 5; i++)
list.add(exec.submit(new simpleCallable()));
for(Future<Integer> f : list)
try {
println(f.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
} finally {
exec.shutdown();
}
}
}
Runnable是执行工作的独立任务,但是它不会返回任何值,而实现Callable<V>可以在call()方法中产生类型为V的对象并返回其引用(我觉得这样说会比“返回类型为V的对象”更合适一些),并且必须使用ExecutorService。submit()来调用它;submit方法会产生Future对象并返回其引用,第一个for并不会被阻塞;可以用isDone()来查询任务是否完成,或者直接使用get()来取得结果,当get()时任务未完成则会阻塞get()。
4.5使用ThreadFactory
class simpleThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
return t;
}
}
public class test {
public static void main(String[] args) {
ExecutorService exec = Executors.newCachedThreadPool(new simpleThreadFactory());
exec.execute(new simpleRunnable());
exec.shutdown();
}
}
Java 创建线程的方法的更多相关文章
- java创建线程的方法
1.1 创建线程 1.1.1 无返回值的线程创建 package com.first; public class ThreadTest { public static void ma ...
- -1-5 java 多线程 概念 进程 线程区别联系 java创建线程方式 线程组 线程池概念 线程安全 同步 同步代码块 Lock锁 sleep()和wait()方法的区别 为什么wait(),notify(),notifyAll()等方法都定义在Object类中
本文关键词: java 多线程 概念 进程 线程区别联系 java创建线程方式 线程组 线程池概念 线程安全 同步 同步代码块 Lock锁 sleep()和wait()方法的区别 为什么wait( ...
- 【Java 线程的深入研究1】Java 提供了三种创建线程的方法
Java 提供了三种创建线程的方法: 通过实现 Runnable 接口: 通过继承 Thread 类本身: 通过 Callable 和 Future 创建线程. 1.通过实现 Runnable 接口来 ...
- 程序员:java中直接或间接创建线程的方法总结
在java开发中,经常会涉及多线程的编码,那么通过直接或间接创建线程的方法有哪些?现整理如下: 1.继承Thread类,重写run()方法 class Worker extends Thread { ...
- java创建线程的四种方法
第一种: 通过继承Thread类创建线程 第二种: 通过实现Runnable接口创建线程 这两种早已烂记于心,这里就不作过多的介绍, 主要介绍其源码 Thread类 implements Runna ...
- Java并发编程:Java创建线程的三种方式
目录 引言 创建线程的三种方式 一.继承Thread类 二.实现Runnable接口 三.使用Callable和Future创建线程 三种方式的对比 引言 在日常开发工作中,多线程开发可以说是必备技能 ...
- Java创建线程的三种主要方式
Java创建线程的主要方式 一.继承Thread类创建 通过继承Thread并且重写其run(),run方法中即线程执行任务.创建后的子类通过调用 start() 方法即可执行线程方法. 通过继承Th ...
- Java创建线程的四种方式
Java创建线程的四种方式 1.继承Thread类创建线程 定义Thread类的子类,并重写该类的run方法,run()方法的内容就是该线程执行的内容 创建Thread子类的实例,即创建了线程对象. ...
- 当阿里面试官问我:Java创建线程有几种方式?我就知道问题没那么简单
这是最新的大厂面试系列,还原真实场景,提炼出知识点分享给大家. 点赞再看,养成习惯~ 微信搜索[武哥聊编程],关注这个 Java 菜鸟. 昨天有个小伙伴去阿里面试实习生岗位,面试官问他了一个老生常谈的 ...
随机推荐
- 可能是国内最火的开源项目 —— C/C++ 篇
程序员们,在北上广你还能买房吗? >>> 推荐阅读: 可能是最火的开源项目 -- Java 篇 可能是国内最火的开源项目 -- PHP 篇 可能是国内最火的开源项目 -- Pyt ...
- Java——Iterate through a HashMap
遍历Map import java.util.*; public class IterateHashMap { public static void main(String[] args) { Map ...
- 【bzoj3376-方块游戏】带权并查集
题意: n块积木,m个操作或询问.每次移动积木的时候,约翰会选择两块积木X,Y,把X搬到Y的上方.如果X已经和其它积木叠在一起了,那么应将这叠积木整体移动到Y的上方:如果Y已经和其它积木叠在一起了的, ...
- 【CodeForces】601 D. Acyclic Organic Compounds
[题目]D. Acyclic Organic Compounds [题意]给定一棵带点权树,每个点有一个字符,定义一个结点的字符串数为往下延伸能得到的不重复字符串数,求min(点权+字符串数),n&l ...
- 【BZOJ】1666 [Usaco2006 Oct]Another Cow Number Game 奶牛的数字游戏
[算法]贪心&&堆 [题解]反过来看就是合并任意两块木板,花费为木板长度之和. 显然从最小的两块开始合并即可,用堆(优先队列)维护. 经典DP问题石子归并是只能合并相邻两堆石子,所以不 ...
- 正则表达式实现将html文本转换为纯文本格式(将html字符串转换为纯文本方法)
Regex regex = new Regex("<.+?>", RegexOptions.IgnoreCase); string strOutput = regex. ...
- 我的spring boot,杨帆、起航!
快速新建一个spring boot工程可以去http://start.spring.io/这个网址,配置完后会自动下载一个工程的压缩包,解压后导入相关ide工具即可使用. 工程中会自带一个class启 ...
- Spring Cloud Netflix之Eureka 相关概念
为什么不应该使用ZooKeeper做服务发现 英文链接:Eureka! Why You Shouldn’t Use ZooKeeper for Service Discovery:http://www ...
- 【EverydaySport】健身笔记——静态牵拉
静态牵拉一般在运动后进行,可以有效的提高肌肉的柔韧性和关节的灵活性,预防和缓解疼痛. 每个动作达到自己活动范围的最大,有牵拉感即说明有效,静态保持至少30秒,切勿震荡,进行2组. 1 大腿前群牵拉 2 ...
- in_device结构和in_ifaddr结构
/* ip配置块 */ struct in_device { /* 二层设备 */ struct net_device *dev; /* 引用计数 */ atomic_t refcnt; /* 是否正 ...