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 菜鸟. 昨天有个小伙伴去阿里面试实习生岗位,面试官问他了一个老生常谈的 ...
随机推荐
- 51Nod 1003 阶乘后面0的数量 | 思维
题意:n的阶乘后面0的个数,如果直接算出阶乘再数0的数量一定会超时的. 因为10=2*5,所以求出5贡献的次数就行. #include "bits/stdc++.h" using ...
- 【洛谷 P1707】 刷题比赛 (矩阵加速)
题目连接 很久没写矩阵加速了,复习一下,没想到是一道小毒瘤题. 状态矩阵\(a[k],b[k],c[k],a[k+1],b[k+1],c[k+1],k,k^2,w^k,z^k,1\) 转移矩阵 0, ...
- Javascript prototype 及 继承机制的设计思想
我一直很难理解Javascript语言的继承机制. 它没有"子类"和"父类"的概念,也没有"类"(class)和"实例" ...
- js_返回上一页(兼容苹果手机)
返回上一页功能是常见的功能. 常用的有以下三种代码: window.history.go(-1); //返回上一页 window.history.back(); //返回上一页 //如果要强行刷新的话 ...
- js按值及引用传递中遇到的小问题
有人闲的蛋疼,非要在函数中使用如下方式传值,尼玛一下把我搞糊涂了.于是决定发挥打破沙锅问到底的精神搞清楚它. var a = 1,b = [], c = {}; function f(a, b, c) ...
- [NOIP2011]刷水
前几天做了NOIP2011的题,感觉不是那么难. 这边先做了两天的前两题,T3还没打. D1T1:顺次读入,分别判断是否覆盖即可,照例大水: #include<cstdio> ],b[], ...
- mysql not null default / default
not null default 说明不能是NULL, 并设置默认值 default 设置默认值 , 但值也可能是NULL mysql> create table test (id int, n ...
- Perl6 Bailador框架(1):开始
use v6; use Bailador; get '/' => sub { '<h1><center>Hello, World</center></h ...
- JS中,children和childNodes的不同之处
<ul id="ul"><li></li><li></li><li><span></spa ...
- Python模块学习 - openpyxl
openpyxl模块介绍 openpyxl模块是一个读写Excel 2010文档的Python库,如果要处理更早格式的Excel文档,需要用到额外的库,openpyxl是一个比较综合的工具,能够同时读 ...