彻底明白Java的多线程-实现多线程及线程的同步

2014-11-23 23:19:11 · 作者: · 浏览: 0

一. 实现多线程


1. 虚假的多线程
例1:
  1. public class TestThread
  2. {
  3. int i=0, j=0;
  4. public void go(int flag){
  5. while(true){
  6. try{
  7. Thread.sleep(100);
  8. }
  9. catch(InterruptedException e){
  10. System.out.println("Interrupted");
  11. }
  12. if(flag==0)
  13. i++;
  14. System.out.println("i=" + i);
  15. }
  16. else{
  17. j++;
  18. System.out.println("j=" + j);
  19. }
  20. }
  21. }
  22. public static void main(String[] args){
  23. new TestThread().go(0);
  24. new TestThread().go(1);
  25. }
  26. }

上面程序的运行结果为:
i=1
i=2
i=3
。。。
结果将一直打印出I的值。我们的意图是当在while循环中调用sleep()时,另一个线程就将起动,打印出j的值,但结果却并不是这样。关于sleep()为什么不会出现我们预想的结果,在下面将讲到。
2. 实现多线程
通过继承class Thread或实现Runnable接口,我们可以实现多线程
2.1 通过继承class Thread实现多线程
class Thread中有两个最重要的函数run()和start()。
1) run()函数必须进行覆写,把要在多个线程中并行处理的代码放到这个函数中。
2) 虽然run()函数实现了多个线程的并行处理,但我们不能直接调用run()函数,而是通过调用start()函数来调用run()函数。在调用start()的时候,start()函数会首先进行与多线程相关的初始化(这也是为什么不能直接调用run()函数的原因),然后再调用run()函数。
例2:
  1. public class TestThread extends Thread{
  2. private static int threadCount = 0;
  3. private int threadNum = ++threadCount;
  4. private int i = 5;
  5. public void run(){
  6. while(true){
  7. try{
  8. Thread.sleep(100); 
  9. }
  10. catch(InterruptedException e){
  11. System.out.println("Interrupted");
  12. }
  13. System.out.println("Thread " + threadNum + " = " + i);
  14. if(--i==0) return;
  15. }
  16. }
  17. public static void main(String[] args){
  18. for(int i=0; i<5; i++)
  19. new TestThread().start();
  20. }
  21. }

运行结果为:
T