zoukankan      html  css  js  c++  java
  • 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();
    }
    }

    ---
    可以转载, 但必须以超链接形式标明文章原始出处和作者信息及版权声明
  • 相关阅读:
    详解CSS中:nth-child的用法
    网站哀悼变灰代码集合 兼容所有浏览器的CSS变暗代码
    简单CSS3实现炫酷读者墙
    CSS常用浮出层的写法
    五种方法让CSS实现垂直居中
    网页前端开发:微博CSS3适用细节初探
    CSS代码实例:用CSS代码写出的各种形状图形
    10个CSS简写及优化技巧
    25个站长必备的SEO优化工具
    40个让你的网站屌到爆的jQuery插件
  • 原文地址:https://www.cnblogs.com/null00/p/2065089.html
Copyright © 2011-2022 走看看