日期:2014-05-20  浏览次数:20645 次

java多线程学习笔记!
本帖最后由 u011702993 于 2013-08-15 23:06:03 编辑

以前没有写笔记的习惯,现在慢慢的发现及时总结是多么的重要了,呵呵。
这一篇文章主要关于java多线程,自己网上找了一些资料在这里做成笔记。
同时也算是我以后复习的资料吧,呵呵,以后请大家多多指教。


Java多线程



在Java中,多线程有两种实现方法,一种是继承Thread类或者实现Runnable接口。
对于直接继承Thread类来说,代码大致如下:

class 类名 extends Thread{
 
  public void run(){
    //方法体
  }

}


/**
 *  继承Thread类,直接调用run方法
 **/
class hello extends Thread{
  public hello(){

  }

  private String name;

  public hello(String name){
    this.name=name;
  }

  public void run(){
    for(int i=0;i<5;i++){
      System.out.println(name+"运行"+i);
    }
  }

  public static void main(String[] args){
    hello h1=new hello("A");
    hello h2=new hello("B");
    h1.run();
    h2.run()
  }
}

【运行结果】:
A运行      0
A运行      1
A运行      2
A运行      3
A运行      4
B运行      0
B运行      1
B运行      2
B运行      3
B运行      4
我们会发现这些都是顺序执行的,说明我们调用的方法不对,应该调用start()
把上面的main方法改为:

public static void main(String[] args){
  hello h1=new hello("A");
  hello h2=new hello("B");
  h1.start();
  h2.start();
}

然后运行你就会发现它的输出结果基本每次都是不一样的。

注意:虽然这里调用了start()方法,但是实际上调用的还是run()方法的主体。
并且start方法重复调用会报异常。

下面通过实现Runnable接口:

class 类名 implements Runnable{
  public void run(){
    //方法体
  }
}

实现Runnable接口小例子: