Java Thread | 线程

本文介绍了Java中多线程的基本概念,包括线程的好处、生命周期、实现方式等,并详细讲解了同步、锁机制以及线程间通信等内容。

Why Thread

  • Single-threaded application:
    1. leads to poor response
    2. has poor prefomance
    3. has poor utilization of CPU resources

Thread in Java

  • A/multiple thread is one/multiple task of an/- execution flow, flowing from beginning to end
  • Organzied programs into logically seperate paths
  • Can preform independent
  • Share access to common resources.



  • Language and api provide concurrency in JAVA
  • Multiple thread if execution
  • Each thread has its own method-call stack
  • 程序计数器

Life cycle of a thread
  • Controlled by JVM
  1. New
    在调取start()之前, 创建 thread class 的实例
  2. Runnable
    调取start()之后
  3. Running
    scheduler被选中
  4. Non-Runnable(Blocked)
    thread alive,but currently not eligible to run
  5. Terminated
    run()还在的时候死掉了

Syntax:
  1. extend Thread Class
public class ClassName extends Thread{
	public void run(){
	//run 必须override
	}
}
  1. runnable obj
public class ClassName implements Runnable{
	public void run(){
	//run 必须实现 和 override
	//只有一个run()方法
	}
}

Thread Schedular
  • JVM
  • Decides which thread should run
  • Random select
  • Preemptive: priority
  • Time slicing scheduling:predifine->reenter

Intrinsic lock
  • Protect multi-thread task
  • Fac to every obj
  • Dadada

好处
  • prevent thread interference
  • Prevent consistency problem

同步种类
  • By process
  • By Thread
  • (inter-thread communication)
  • Mutual exclusive
Synchronized void method(){
}

Synchronized(this){
}

Sleep()
  • Purpose: use to sleep a thread for a setting time.
  • Implimentation:
// runnable implements
// main()
@ Override
public void run(){
// some code here
	try{
		Thread.sleep(1000);//sleep for 1 second
		}catch(InterruptedException e{
			System.out.println(e);
		}
// some code here
}

join()
  • Purpose: use to forced one thread to wait for antoher thread to finish.
  • Implimentation:
 // main()
 // some code here
 thread1.start()
 try{
 	thread1.join();
 }catch(InterruptedException e{
			System.out.println(e);
}
thread2.start();
//some code here

interrupt()
  • use to “terminated” the status of a task
  • 常用表达 Thread.CurrentThread().isInterrupted()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值