手机
当前位置:查字典教程网 >编程开发 >Java >Java并发程序入门介绍
Java并发程序入门介绍
摘要:今天看了看Java并发程序,写一写入门程序,并设置了线程的优先级。classElemimplementsRunnable{publicsta...

今天看了看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(); } }

【Java并发程序入门介绍】相关文章:

Java线程关闭的3种方法

Java实现几种常见排序算法代码

java中定义常量方法介绍

Java程序执行时间的2种简单方法

Java线程中sleep和wait的区别详细介绍

基于Java注解(Annotation)的自定义注解入门介绍

java调用Oracle存储过程的方法实例

java之路径分隔符介绍

java 图片加水印实例代码

Java 反射之私有字段和方法详细介绍

精品推荐
分类导航