Java 多线程

1。Thread类和Runnable接口

2。主线程:用Thread的static Thread currentThread()方法获得

3。通过实现Runnable接口创建线程:实现Runnable接口的run方法。新线程在run()方法返回时结束。注意用这种方法创建进程时,在实现Runnable接口的类的构造函数里通常需要用new Thread新建一个线程,并用start函数开启这个线程。实质上,start函数执行的就是对run函数的调用。如:


class DemoThread implements Runnable{
 Thread t;
 static int ThreadNum = 1;
 
 public DemoThread() throws Exception{
  t = new Thread(this, "Demo Thread");
  System.out.println("new Child Thread:" + t);
  ThreadNum++;
  t.start();  
 }
 
 public void run(){
  for(int i = 5; i > 0; i--){
  System.out.println("ChildThread: " + i);
  try{
  Thread.sleep(500);
  }catch(Exception e){
   System.out.println("childThead Exception");
  }
  
  }
  System.out.println("Exit ChildThread!");
 }
 }
 
public class NewThread{  
 public static void main(String[] args) throws Exception{
  
  DemoThread nt = new DemoThread();  
  DemoThread nt2 = new DemoThread();
  for(int i = 5; i > 0; i--){
   System.out.println("MainThread:" + i);
   Thread.currentThread().sleep(1000);
  }
  System.out.println("Exit MainThread!");
 } 
}

4。扩展(继承)Thread类新建线程,如:

public class TestThread extends Thread{
 public TestThread(){
  super("Demo Thread"); //注意这里
  System.out.println("ChildThread Creadted:" + this);
  start();
 }
  public void run(){
  ; //具体实现略
 }
 }

5。主线程一般必须最后结束。isAlive()函数判断一个线程是否已经结束。join()方法可用来等待它调用的线程终止。

6。线程优先级:get/setPriority方法。

7。同步方法:保证同一时刻只有一个线程访问方法,在方法定义前面加关键字:synchronized。

8。同步语句:将对外部类的方法的访问置于一个synchronized块中。synchronized(object){...;} 其中object是需要同步的对象的引用。

9。线程内通信:为了使用异步访问。wait()方法告诉调用这个函数的进程放弃监控器并进入睡眠状态,直到其他进程进入同一监控器并调用notify方法。notify方法唤醒第一个等待同一对象的线程。notify方法唤醒所有对同一个对象调用wait()的线程,最高优先级的先运行。

10。暂停、恢复、停止线程:不能使用suspend,resume和stop方法。应该用wait和notify方法。

 

 

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值