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 菜鸟. 昨天有个小伙伴去阿里面试实习生岗位,面试官问他了一个老生常谈的 ...
随机推荐
- python基础---输入输出
1.输入字符串. name=input() or name=input('please input a string') 这样可以接收一个字符串,包括空格,都可以输入.只有回车不接受,作为结束符, ...
- POJ 2891- Strange Way to Express Integers CRT 除数非互质
题意:给你余数和除数求x 注意除数不一定互质 思路:不互质的CRT需要的是将两个余数方程合并,需要用到扩展GCD的性质 合并互质求余方程 m1x -+ m2y = r2 - r1 先用exgcd求出特 ...
- Cppcheck代码分析上
1.检查点 1.自动变量检查: 返回自动变量(局部变量)指针: 2.越界检查:数组越界返回自动变量(局部变量)指针: 3.类检查:构造函数初始化: 4.内存泄露检查: 5.空指针检查: 6.废弃函数 ...
- 【CODEVS】3546 矩阵链乘法
[算法]区间DP [题解] 注意先输出右括号后输出左括号. f[i][i+x-1]=min(f[i][i+x-1],f[i][j]+f[j+1][i+x-1]+p[i]*p[j+1]*p[i+x]) ...
- MySQL数据库运行环境的搭建
第一步:安装wampserver2.5-Apache-2.4.9-Mysql-5.6.17-php5.5.12-64b文件,安装过程中可能会遇到问题,把遇到的问题代码复制粘贴到360人工服务,查找方案 ...
- POJ 3276 Face The Right Way (尺取法)
题目链接 Description Farmer John has arranged his N (1 ≤ N ≤ 5,000) cows in a row and many of them are f ...
- 4、什么是事务?MySQL如何支持事务?
什么是事务? 事务是由一步或几步数据库操作序列组成逻辑执行单元,这系列操作要么全部执行,要么全部放弃执行.程序和事务是两个不同的概念.一般而言:一段程序中可能包含多个事务.(说白了就是几步的数据库操作 ...
- poj 2000 Gold Coins
题目链接:http://poj.org/problem?id=2000 题目大意:求N天得到多少个金币,第一天得到1个,第二.三天得到2个,第四.五.六天得到3个....以此类推,得到第N天的金币数. ...
- vue-实现倒计时功能
JavaScript 创建一个 countdown 方法,用于计算并在控制台打印距目标时间的日.时.分.秒数,每隔一秒递归执行一次. msec 是当前时间距目标时间的毫秒数,由时间戳相减得到,我们将以 ...
- PHP路由代码
<?php /** * 路由 * @author 角度 QQ:1286522207 * */ class Dispatcher extends Action { private ...