服务器之家:专注于服务器技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - Java实现在不同线程中运行的代码实例

Java实现在不同线程中运行的代码实例

2020-09-10 13:50FrankYou Java教程

这篇文章主要介绍了Java实现在不同线程中运行的代码,结合具体实例形式分析了java多线程操作的相关实现技巧,需要的朋友可以参考下

本文实例讲述了Java实现在不同线程运行的代码。分享给大家供大家参考,具体如下:

Java实现在不同线程中运行的代码实例

start()方法开始为一个线程分配CPU时间,这导致对run()方法的调用。

代码1

?
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
package Threads;
/**
 * Created by Frank
 */
public class ThreadsDemo1 extends Thread {
 private String msg;
 private int count;
 public ThreadsDemo1(final String msg, int n) {
  this.msg = msg;
  count = n;
  setName(msg + " runner Thread");
 }
 public void run() {
  while (count-- > 0) {
   System.out.println(msg);
   try {
    Thread.sleep(100);
   } catch (InterruptedException e) {
    return;
   }
  }
  System.out.println(msg + " all done.");
 }
 public static void main(String[] args) {
  new ThreadsDemo1("Hello from X", 10).start();
  new ThreadsDemo1("Hello from Y", 15).start();
 }
}

代码2:

?
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
package Threads;
/**
 * Created by Frank
 */
public class ThreadsDemo2 implements Runnable {
 private String msg;
 private Thread t;
 private int count;
 public static void main(String[] args) {
  new ThreadsDemo2("Hello from X", 10);
  new ThreadsDemo2("Hello from Y", 15);
 }
 public ThreadsDemo2(String m, int n) {
  this.msg = m;
  count = n;
  t = new Thread(this);
  t.setName(msg + "runner Thread");
  t.start();
 }
 public void run() {
  while (count-- > 0) {
   System.out.println(msg);
   try {
    Thread.sleep(100);
   } catch (InterruptedException e) {
    return;
   }
  }
  System.out.println(msg + " all done.");
 }
}

代码3:

?
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
package Threads;
/**
 * Created by Frank
 */
public class ThreadsDemo3 {
 private int count;
 public static void main(String[] args) {
  new ThreadsDemo3("Hello from X", 10);
  new ThreadsDemo3("Hello from Y", 15);
 }
 public ThreadsDemo3(final String msg, int n) {
  this.count = n;
  Thread t = new Thread(new Runnable() {
   public void run() {
    while (count-- > 0) {
     System.out.println(msg);
     try {
      Thread.sleep(100);
     } catch (InterruptedException e) {
      return;
     }
    }
    System.out.println(msg + " all done.");
   }
  });
  t.setName(msg + " runner Thread");
  t.start();
 }
}

eclipse运行结果如下:

Java实现在不同线程中运行的代码实例

希望本文所述对大家java程序设计有所帮助。

延伸 · 阅读

精彩推荐