为了偷懒少敲几个字这里我写了一个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 创建线程的方法的更多相关文章

  1. java创建线程的方法

    1.1      创建线程 1.1.1     无返回值的线程创建 package com.first; public class ThreadTest { public static void ma ...

  2. -1-5 java 多线程 概念 进程 线程区别联系 java创建线程方式 线程组 线程池概念 线程安全 同步 同步代码块 Lock锁 sleep()和wait()方法的区别 为什么wait(),notify(),notifyAll()等方法都定义在Object类中

     本文关键词: java 多线程 概念 进程 线程区别联系 java创建线程方式 线程组 线程池概念 线程安全 同步 同步代码块 Lock锁  sleep()和wait()方法的区别 为什么wait( ...

  3. 【Java 线程的深入研究1】Java 提供了三种创建线程的方法

    Java 提供了三种创建线程的方法: 通过实现 Runnable 接口: 通过继承 Thread 类本身: 通过 Callable 和 Future 创建线程. 1.通过实现 Runnable 接口来 ...

  4. 程序员:java中直接或间接创建线程的方法总结

    在java开发中,经常会涉及多线程的编码,那么通过直接或间接创建线程的方法有哪些?现整理如下: 1.继承Thread类,重写run()方法 class Worker extends Thread { ...

  5. java创建线程的四种方法

    第一种:  通过继承Thread类创建线程 第二种: 通过实现Runnable接口创建线程 这两种早已烂记于心,这里就不作过多的介绍, 主要介绍其源码 Thread类 implements Runna ...

  6. Java并发编程:Java创建线程的三种方式

    目录 引言 创建线程的三种方式 一.继承Thread类 二.实现Runnable接口 三.使用Callable和Future创建线程 三种方式的对比 引言 在日常开发工作中,多线程开发可以说是必备技能 ...

  7. Java创建线程的三种主要方式

    Java创建线程的主要方式 一.继承Thread类创建 通过继承Thread并且重写其run(),run方法中即线程执行任务.创建后的子类通过调用 start() 方法即可执行线程方法. 通过继承Th ...

  8. Java创建线程的四种方式

    Java创建线程的四种方式 1.继承Thread类创建线程 定义Thread类的子类,并重写该类的run方法,run()方法的内容就是该线程执行的内容 创建Thread子类的实例,即创建了线程对象. ...

  9. 当阿里面试官问我:Java创建线程有几种方式?我就知道问题没那么简单

    这是最新的大厂面试系列,还原真实场景,提炼出知识点分享给大家. 点赞再看,养成习惯~ 微信搜索[武哥聊编程],关注这个 Java 菜鸟. 昨天有个小伙伴去阿里面试实习生岗位,面试官问他了一个老生常谈的 ...

随机推荐

  1. [洛谷P2852] [USACO06DEC]牛奶模式Milk Patterns

    洛谷题目链接:[USACO06DEC]牛奶模式Milk Patterns 题目描述 Farmer John has noticed that the quality of milk given by ...

  2. C11性能之道:标准库优化

    1.emplace_back减少内存拷贝和移动 emplace_back能通过参数构造对象,不需要拷贝或者移动内存,相比pusk_back能更好的避免内存的拷贝和移动,使容器插入元素性能得到进一步提升 ...

  3. 【BZOJ】1700: [Usaco2007 Jan]Problem Solving 解题

    [题意]给定n道题,每月末发放工资m,要求从1解到n,每道题需要在当月初付费ai,下月初付费bi,多道题可以安排在同月,求最少月数. [算法]DP [题解]参考自:[bzoj1700]Problem ...

  4. 继承自UITableView的类自带tableView属性,不需要在创建该属性,因为父类UITableView已经创建.

      继承自UITableView的类自带tableView属性,不需要在创建该属性,因为父类UITableView已经创建.   https://www.evernote.com/shard/s227 ...

  5. 【CF1009F】 Dominant Indices (长链剖分+DP)

    题目链接 \(O(n^2)\)的\(DP\)很容易想,\(f[u][i]\)表示在\(u\)的子树中距离\(u\)为\(i\)的点的个数,则\(f[u][i]=\sum f[v][i-1]\) 长链剖 ...

  6. JQuery-Ajax后台提交数据与获取数据 Java代码

    function jqajax(){ var urlName = $("#urlName").val(); var urla = $("#url").val() ...

  7. jeecg3.7中DictSelect数据字典下拉选择框的用法

    1.参数 属性名                      类型        描述                                                           ...

  8. Quartz的Properties文件解析

    将可变信息放在properties文件是使配置更加灵活. 1.文档位置和加载顺序 1. StdSchedulerFactory默认加载quartz包下的quartz.properties文件,如果我们 ...

  9. Python【模块】importlib,requests

    内容概要:      模仿django中间件的加载方式      importlib模块      requests模块  rsplit()   用实际使用的理解来解释两个模块 importlib模块 ...

  10. python基础===getattr()函数使用方法

    getattr(object, name[,default]) 获取对象object的属性或者方法,如果存在打印出来,如果不存在,打印出默认值,默认值可选.需要注意的是,如果是返回的对象的方法,返回的 ...