为了偷懒少敲几个字这里我写了一个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. 【设计模式】 模式PK:观察者模式VS责任链模式

    1.概述 为什么要把观察者模式和责任链模式放在一起对比呢?看起来这两个模式没有太多的相似性,真没有吗?回答是有.我们在观察者模式中也提到了触发链(也叫做观察者链)的问题,一个具体的角色既可以是观察者, ...

  2. Linux之防火墙与端口

    1.关闭所有的 INPUT FORWARD OUTPUT 只对某些端口开放.下面是命令实现: iptables -P INPUT DROPiptables -P FORWARD DROPiptable ...

  3. iOS-Apple苹果iPhone开发公开API

      iOS-Apple苹果iPhone开发 //技术博客http://www.cnblogs.com/ChenYilong/   新浪微博http://weibo.com/luohanchenyilo ...

  4. performSelector支持多参数

    默认的performSelector支持最多传递两个参数,要想传递超过两个的参数,需要使用NSInvocation来模拟performSelector的行为,如下: - (id)performSele ...

  5. 密码本(无bug版)

    main.cpp #include <stdio.h> #include <stdlib.h> #include "data.h" #include &qu ...

  6. 一键前端代理,一行命令开启nginx容器,代理前端页面

    我们在前端开发的过程中,在对接口时候,往往需要跨域请求,那么及其简便的方法就是使用nginx反向代理,但是存在几点缺点 1.在新的一个项目下,我们需要找到安装nginx目录的nginx.conf文件并 ...

  7. Java案例之随机验证码功能实现

    实现的功能比较简单,就是随机产生了四个字符然后输出.效果图如下,下面我会详细说一下实现这个功能用到了那些知识点,并且会把 这些知识点详细的介绍出来.哈哈 ,大神勿喷,对于初学Java的人帮助应该蛮大的 ...

  8. [转]python os模块 常用命令

    python编程时,经常和文件.目录打交道,这是就离不了os模块.os模块包含普遍的操作系统功能,与具体的平台无关.以下列举常用的命令 1. os.name()——判断现在正在实用的平台,Window ...

  9. $(document).ready 和 window.onload 的区别

    1.相同点 两者都用于在网页加载完后执行相应代码块. 2.不同点 window.onload 在创建完 DOM 树后,所有外部资源(图片.Flash 动画等)加载完成,且整个页面在浏览器窗口中显示完毕 ...

  10. 64_j1

    JSCookMenu-2.0.4-13.fc26.noarch.rpm 13-Feb-2017 22:06 38098 Java-WebSocket-1.3.1-0.2.git58d1778.fc24 ...