gpt4 book ai didi

Java并发程序入门介绍

转载 作者:qq735679552 更新时间:2022-09-29 22:32:09 24 4
gpt4 key购买 nike

CFSDN坚持开源创造价值,我们致力于搭建一个资源共享平台,让每一个IT人在这里找到属于你的精彩世界.

这篇CFSDN的博客文章Java并发程序入门介绍由作者收集整理,如果你对这篇文章有兴趣,记得点赞哟.

今天看了看Java并发程序,写一写入门程序,并设置了线程的优先级.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
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来管理线程.

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
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并发程序入门介绍的文章就讲到这里了,如果你想了解更多关于Java并发程序入门介绍的内容请搜索CFSDN的文章或继续浏览相关文章,希望大家以后支持我的博客! 。

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com