zookeeper python接口实例详解
195
2023-08-03
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 = http://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();
}
}
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~