Java并發(fā)程序入門介紹
更新時間:2015年03月26日 21:11:51 作者:Microgoogle
這篇文章主要介紹了Java并發(fā)程序入門 ,需要的朋友可以參考下
今天看了看Java并發(fā)程序,寫一寫入門程序,并設置了線程的優(yōu)先級。
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();
}
}
}
由于機器很強悍,所以先開始并沒看到并發(fā)的效果,感覺是按順序執(zhí)行的,所以在中間加了浮點數的運算來延遲時間。
當然,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如何配置不同環(huán)境的配置文件
,springboot支持通過不同的profile來配置不同環(huán)境的配置,下面就大致介紹一下yml配置文件跟properties配置文件怎么使用profile配置不同環(huán)境的配置文件2018-01-01
Java獲取當前系統(tǒng)事件System.currentTimeMillis()方法
下面小編就為大家?guī)硪黄狫ava獲取當前系統(tǒng)事件System.currentTimeMillis()方法。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-06-06
如何優(yōu)雅的拋出Spring Boot注解的異常詳解
這篇文章主要給大家介紹了關于如何優(yōu)雅的拋出Spring Boot注解的異常的相關資料,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2018-12-12
Java多線程并發(fā)開發(fā)之DelayQueue使用示例
這篇文章主要為大家詳細介紹了Java多線程并發(fā)開發(fā)之DelayQueue使用示例,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-09-09

