Java Hour 27 Concurrent
有句名言,叫做10000小时成为某一个领域的专家。姑且不辩论这句话是否正确,让我们到达10000小时的时候再回头来看吧。
27 Hours.
本小时主要过一下多线程相关的基本API.
Defining tasks
package mike.qian.hello;
public class LiftOff implements Runnable {
    protected int countDown = 10; // Default
    private static int taskCount = 0;
    private final int id = taskCount++;
    public LiftOff() {
    }
    public LiftOff(int countDown) {
        this.countDown = countDown;
    }
    public String status() {
        return "#" + id + "(" + (countDown > 0 ? countDown : "Liftoff!") + "), ";
    }
    public void run() {
        while (countDown-- > 0) {
            System.out.print(status());
            Thread.yield();
        }
    }
}
一个线程主要是为了驱动一个task. 只要实现一个Runnable 接口就表示这是一个task.
Thread.yield 这个是可选了,表明允许CPU从当前线程中滚出去干其他事情去。
package mike.qian.hello;
public class Application {
    public static void main(String[] args) {
        Thread t = new Thread(new LiftOff());
        t.start();
        System.out.println("Waiting for LiftOff");
    }
}
package mike.qian.hello;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Application {
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++)
            exec.execute(new LiftOff());
        exec.shutdown();
        System.out.println("Waiting for LiftOff");
    }
}
带返回值的线程
package mike.qian.hello;
import java.util.concurrent.Callable;
class TaskWithResult implements Callable<String> {
    private int id;
    public TaskWithResult(int id) {
        this.id = id;
    }
    public String call() {
        return "result of TaskWithResult " + id;
    }
}
package mike.qian.hello;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Application {
    public static void main(String[] args) {
        ExecutorService exec = Executors.newCachedThreadPool();
        ArrayList<Future<String>> results = new ArrayList<Future<String>>();
        for (int i = 0; i < 10; i++)
            results.add(exec.submit(new TaskWithResult(i)));
        for (Future<String> fs : results)
            try {
                // get() blocks until completion:
                System.out.println(fs.get());
            } catch (InterruptedException e) {
                System.out.println(e);
                return;
            } catch (ExecutionException e) {
                System.out.println(e);
            } finally {
                exec.shutdown();
            }
    }
}
看到这个future, 瞬间石化了,好山寨的命名。
守护线程
守护线程就是后台线程,当所有前台线程退出后,程序将退出。
内部类的使用
package mike.qian.hello;
import java.util.concurrent.*;
import static java.lang.System.out;
// Using a named inner class:
class InnerThread1 {
    private int countDown = 5;
    private Inner inner;
    private class Inner extends Thread {
        Inner(String name) {
            super(name);
            start();
        }
        public void run() {
            try {
                while (true) {
                    out.println(this);
                    if (--countDown == 0)
                        return;
                    sleep(10);
                }
            } catch (InterruptedException e) {
                out.println("interrupted");
            }
        }
        public String toString() {
            return getName() + ": " + countDown;
        }
    }
    public InnerThread1(String name) {
        inner = new Inner(name);
    }
}
// Using an anonymous inner class:
class InnerThread2 {
    private int countDown = 5;
    private Thread t;
    public InnerThread2(String name) {
        t = new Thread(name) {
            public void run() {
                try {
                    while (true) {
                        out.println(this);
                        if (--countDown == 0)
                            return;
                        sleep(10);
                    }
                } catch (InterruptedException e) {
                }
            }
            public String toString() {
                return getName() + ": " + countDown;
            }
        };
        t.start();
    }
}
// Using a named Runnable implementation:
class InnerRunnable1 {
    private int countDown = 5;
    private Inner inner;
    private class Inner implements Runnable {
        Thread t;
        Inner(String name) {
            t = new Thread(this, name);
            t.start();
        }
        public void run() {
            try {
                while (true) {
                    out.println(this);
                    if (--countDown == 0)
                        return;
                    TimeUnit.MILLISECONDS.sleep(10);
                }
            } catch (InterruptedException e) {
                out.println("sleep() interrupted");
            }
        }
        public String toString() {
            return t.getName() + ": " + countDown;
        }
    }
    public InnerRunnable1(String name) {
        inner = new Inner(name);
    }
}
// Using an anonymous Runnable implementation:
class InnerRunnable2 {
    private int countDown = 5;
    private Thread t;
    public InnerRunnable2(String name) {
        t = new Thread(new Runnable() {
            public void run() {
                try {
                    while (true) {
                        out.println(this);
                        if (--countDown == 0)
                            return;
                        TimeUnit.MILLISECONDS.sleep(10);
                    }
                } catch (InterruptedException e) {
                    out.println("sleep() interrupted");
                }
            }
            public String toString() {
                return Thread.currentThread().getName() + ": " + countDown;
            }
        }, name);
    }
}
// A separate method to run some code as a task:
class ThreadMethod {
    private int countDown = 5;
    private Thread t;
    private String name;
    public ThreadMethod(String name) {
        this.name = name;
    }
    public void runTask() {
        if (t == null) {
            t = new Thread(name) {
                public void run() {
                    try {
                        while (true) {
                            out.println(this);
                            if (--countDown == 0)
                                return;
                            sleep(10);
                        }
                    } catch (InterruptedException e) {
                        out.println("sleep() interrupted");
                    }
                }
                public String toString() {
                    return getName() + ": " + countDown;
                }
            };
            t.start();
        }
    }
}
public class Application {
    public static void main(String[] args) {
        new InnerThread1("InnerThread1");
        new InnerThread2("InnerThread2");
        new InnerRunnable1("InnerRunnable1");
        new InnerRunnable2("InnerRunnable2");
        new ThreadMethod("ThreadMethod").runTask();
    }
} /* (Execute to see output) */// :~
这里包含了内部类,匿名内部类,相关的内容下个小时补上。
后面茫茫多的内容
其实这块东西和.NET 大同小异,但是东西是茫茫多的,暂且略过不表。
Java Hour 27 Concurrent的更多相关文章
- Java集合及concurrent并发包总结(转)
		
Java集合及concurrent并发包总结(转) 1.集合包 集合包最常用的有Collection和Map两个接口的实现类,Colleciton用于存放多个单对象,Map用于存放Key-Valu ...
 - Java并发包concurrent——ConcurrentHashMap
		
转: Java并发包concurrent——ConcurrentHashMap 2018年07月19日 20:43:23 Bill_Xiang_ 阅读数 16390更多 所属专栏: Java Conc ...
 - java多线程管理 concurrent包用法详解
		
我们都知道,在JDK1.5之前,Java中要进行业务并发时,通常需要有程序员独立完成代码实现,当然也有一些开源的框架提供了这些功能,但是这些依然没有JDK自带的功能使用起来方便.而当针对高质量 ...
 - java 线程之concurrent中的常用工具 CyclicBarrier
		
一.CyclicBarrier CyclicBarrier是一个同步辅助类,它允许一组线程互相等待,直到到达某个公共屏障点 (common barrier point).在涉及一组固定大小的线程的程序 ...
 - java 多线程 27 :多线程组件之CountDownLatch
		
前言 在多线程环境下,JDK给开发者提供了许多的组件供用户使用(主要在java.util.concurrent下),使得用户不需要再去关心在具体场景下要如何写出同时兼顾线程安全性与高效率的代码.之前讲 ...
 - 【java多线程】ConCurrent并发包 - Lock详解
		
synchronized的缺陷 我们知道,可以利用synchronized关键字来实现共享资源的互斥访问. Java 5在java.util.concurrent.locks包下提供了另一种来实现 ...
 - Java集合及Concurrent并发包总结
		
1.集合包 集合包最常用的有Collection和Map两个接口的实现类,Colleciton用于存放多个单对象,Map用于存放Key-Value形式的键值对. Collection中最常用的又分为两 ...
 - Java 第27章 JDBC
		
JDBC 模版 JDBC 的工作原理 JDBC API 提供者:Sun公司 内容:供程序员调用的接口与类,集成在java.sql 和javax.sql 包中,如: DriverManager 类 Co ...
 - java基础27 单例集合Collection及其常用方法
		
1.集合 集合是存储对象数据的集合容器 1.1.集合比数组的优势 1.集合可以存储任意类型的数据,数组只能存储同一种数据类型的数据 2.集合的长度是变化的,数组的长度是固定的 1.2.数组:存储 ...
 
随机推荐
- TFS 配置 报表权限问题
			
通过[项目门户网站]访问,却被提示ReportService权限不足时, 提示:处理报表时出错. (rsProcessingAborted) 对数据集 “dsiteration” 执行查询失败 同样 ...
 - python 入门
			
bool t, f = True, False print type(t) # Prints "<type 'bool'>" 字符串 hello = 'hello' ...
 - nginx 支持pathinfo的配置文件
			
location ~ \.php { fastcgi_pass 127.0.0.1:9000; fastcgi_index index.php; include fastcgi_params; set ...
 - WPF 组合快捷键
			
if(e.KeyStates == Keyboard.GetKeyStates(Key.F4) && Keyboard.Modifiers == ModifierKeys.Alt) { ...
 - l来自wentao:项目加入缓存(redis),实时调试时用 -----可视化缓存,flushdb
			
下文来自segmentfault,网站:一个交流网站:https://segmentfault.com/ 在做一个项目时如果加入缓存(例如redis),我如何进行实时调试呢? 缓存 高并发 架构 gz ...
 - JS代码的加载
			
HTML页面中JS的加载原理:在加载HTML页面的时候,当浏览器遇到内嵌的JS代码时会停止处理页面,先执行JS代码,然后再继续解析和渲染页面.同样的情况也发生在外链的JS文件中,浏览器必须先花时间下载 ...
 - 关于Tabula FPGA的话题 (转)
			
最近关注了一下Tabula的产品,特别是这个公司的FPGA.我的关注源于Intel对Tabula的支持.最近和在FPGA方面有较深理解的几位人士简单聊了聊,以下是这次对话的主要内容,希望能对从事这方面 ...
 - POJ 3267 The Cow Lexicon
			
又见面了,还是原来的配方,还是熟悉的DP....直接秒了... The Cow Lexicon Time Limit: 2000MS Memory Limit: 65536K Total Submis ...
 - oracle数据库备份与还原
			
一 关于expdp和impdp 使用EXPDP和IMPDP时应该注意的事项:EXP和IMP是客户端工具程序,它们既可以在客户端使用,也可以在服务端使用.EXPDP和IMPDP是服务端的工具程 ...
 - [Effective JavaScript 笔记] 第4条:原始类型优于封闭对象
			
js有5种原始值类型:布尔值.数字.字符串.null和undefined. 用typeof检测一下: typeof true; //"boolean" typeof 2; //&q ...