技术开发 频道

Java 多线程与并发编程总结

  实现java.lang.Runnable接口

  运行结果:

  main 线程运行开始!

  Thread-0 线程运行开始!

  main 线程运行结束!

  0 Thread-0

  Thread-1 线程运行开始!

  0 Thread-1

  1 Thread-1

  1 Thread-0

  2 Thread-0

  2 Thread-1

  3 Thread-0

  3 Thread-1

  4 Thread-0

  4 Thread-1

  5 Thread-0

  6 Thread-0

  5 Thread-1

  7 Thread-0

  8 Thread-0

  6 Thread-1

  9 Thread-0

  7 Thread-1

  Thread-0 线程运行结束!

  8 Thread-1

  9 Thread-1

  Thread-1 线程运行结束!

  说明:

  TestMitiThread1类通过实现Runnable接口,使得该类有了多线程类的特征。run()方法是多线程程序的一个约定。所有的多线程代码都在run方法里面。Thread类实际上也是实现了Runnable接口的类。

  在启动的多线程的时候,需要先通过Thread类的构造方法Thread(Runnable target) 构造出对象,然后调用Thread对象的start()方法来运行多线程代码。

  实际上所有的多线程代码都是通过运行Thread的start()方法来运行的。因此,不管是扩展Thread类还是实现Runnable接口来实现多线程,最终还是通过Thread的对象的API来控制线程的,熟悉Thread类的API是进行多线程编程的基础。

1 public class TestMitiThread1 implements Runnable {
2
3     public static void main(String[] args) {
4         System.out.println(Thread.currentThread().getName() + " 线程运行开始!");
5         TestMitiThread1 test = new TestMitiThread1();
6         Thread thread1 = new Thread(test);
7         Thread thread2 = new Thread(test);
8         thread1.start();
9         thread2.start();
10         System.out.println(Thread.currentThread().getName() + " 线程运行结束!");
11     }
12
13     public void run() {
14         System.out.println(Thread.currentThread().getName() + " 线程运行开始!");
15         for (int i = 0; i < 10; i++) {
16             System.out.println(i + " " + Thread.currentThread().getName());
17             try {
18                 Thread.sleep((int) Math.random() * 10);
19             } catch (InterruptedException e) {
20                 e.printStackTrace();
21             }
22         }
23         System.out.println(Thread.currentThread().getName() + " 线程运行结束!");
24     }
25 }
26
0
相关文章