Java并发程序入门介绍
更新时间:2015年03月26日 21:11:51 作者:Microgoogle
这篇文章主要介绍了Java并发程序入门 ,需要的朋友可以参考下
今天看了看Java并发程序,写一写入门程序,并设置了线程的优先级。
class Elem implements Runnable{ public static int id = 0; private int cutDown = 5; private int priority; public void setPriority(int priority){ this.priority = priority; } public int getPriority(){ return this.priority; } public void run(){ Thread.currentThread().setPriority(priority); int threadId = id++; while(cutDown-- > 0){ double d = 1.2; while(d < 10000) d = d + (Math.E + Math.PI)/d; System.out.println("#" + threadId + "(" + cutDown + ")"); } } } public class Basic { public static void main(String args[]){ for(int i = 0; i < 10; i++){ Elem e = new Elem(); if(i == 0 ) e.setPriority(Thread.MAX_PRIORITY); else e.setPriority(Thread.MIN_PRIORITY); Thread t = new Thread(e); t.start(); } } }
由于机器很强悍,所以先开始并没看到并发的效果,感觉是按顺序执行的,所以在中间加了浮点数的运算来延迟时间。
当然,main函数里面可以用Executors来管理线程。
import java.util.concurrent.*; class Elem implements Runnable{ public static int id = 0; private int cutDown = 5; private int priority; public void setPriority(int priority){ this.priority = priority; } public int getPriority(){ return this.priority; } public void run(){ Thread.currentThread().setPriority(priority); int threadId = id++; while(cutDown-- > 0){ double d = 1.2; while(d < 10000) d = d + (Math.E + Math.PI)/d; System.out.println("#" + threadId + "(" + cutDown + ")"); } } } public class Basic { public static void main(String args[]){ // for(int i = 0; i < 10; i++){ // Elem e = new Elem(); // if(i == 0 ) // e.setPriority(Thread.MAX_PRIORITY); // else // e.setPriority(Thread.MIN_PRIORITY); // Thread t = new Thread(e); // t.start(); // } ExecutorService exec = Executors.newCachedThreadPool(); for(int i = 0; i < 10; i++){ Elem e = new Elem(); if(i == 0 ) e.setPriority(Thread.MAX_PRIORITY); else e.setPriority(Thread.MIN_PRIORITY); exec.execute(e); } exec.shutdown(); } }
相关文章
Spring Boot使用profile如何配置不同环境的配置文件
,springboot支持通过不同的profile来配置不同环境的配置,下面就大致介绍一下yml配置文件跟properties配置文件怎么使用profile配置不同环境的配置文件2018-01-01Java获取当前系统事件System.currentTimeMillis()方法
下面小编就为大家带来一篇Java获取当前系统事件System.currentTimeMillis()方法。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧2017-06-06
最新评论