欢迎来到代码驿站!

JAVA代码

当前位置:首页 > 软件编程 > JAVA代码

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();
  }
}

上一篇:java swing中实现拖拽功能示例

栏    目:JAVA代码

下一篇:java仿Servlet生成验证码实例详解

本文标题:Java并发程序入门介绍

本文地址:http://www.codeinn.net/misctech/24581.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有