Java并发程序入门介绍
时间:2020-11-20 18:20:11|栏目: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(); } }
阅读排行
- 1Java Swing组件BoxLayout布局用法示例
- 2java中-jar 与nohup的对比
- 3Java邮件发送程序(可以同时发给多个地址、可以带附件)
- 4Caused by: java.lang.ClassNotFoundException: org.objectweb.asm.Type异常
- 5Java中自定义异常详解及实例代码
- 6深入理解Java中的克隆
- 7java读取excel文件的两种方法
- 8解析SpringSecurity+JWT认证流程实现
- 9spring boot里增加表单验证hibernate-validator并在freemarker模板里显示错误信息(推荐)
- 10深入解析java虚拟机