java 多线程的使用_Java的多线程1:线程的使用
概述
public enumState {/*** Thread state for a thread which has not yet started.*/NEW,/*** Thread state for a runnable thread. A thread in the runnable
* state is executing in the Java virtual machine but it may
* be waiting for other resources from the operating system
* such as processor.*/RUNNABLE,/*** Thread state for a thread blocked waiting for a monitor lock.
* A thread in the blocked state is waiting for a monitor lock
* to enter a synchronized block/method or
* reenter a synchronized block/method after calling
* {@linkObject#wait() Object.wait}.*/BLOCKED,/*** Thread state for a waiting thread.
* A thread is in the waiting state due to calling one of the
* following methods:
*
*
{@linkObject#wait() Object.wait} with no timeout*
{@link#join() Thread.join} with no timeout*
{@linkLockSupport#park() LockSupport.park}*
*
*
A thread in the waiting state is waiting for another thread to
* perform a particular action.
*
* For example, a thread that has called Object.wait()
* on an object is waiting for another thread to call
* Object.notify() or Object.notifyAll() on
* that object. A thread that has called Thread.join()
* is waiting for a specified thread to terminate.*/WAITING,/*** Thread state for a waiting thread with a specified waiting time.
* A thread is in the timed waiting state due to calling one of
* the following methods with a specified positive waiting time:
*
*
{@link#sleep Thread.sleep}*
{@linkObject#wait(long) Object.wait} with timeout*
{@link#join(long) Thread.join} with timeout*
{@linkLockSupport#parkNanos LockSupport.parkNanos}*
{@linkLockSupport#parkUntil LockSupport.parkUntil}*
*/TIMED_WAITING,/*** Thread state for a terminated thread.* The thread has completed execution.*/TERMINATED;
}
新建狀態
線程對象創建后,就進入新建狀態? Thread thread = new Thread
就緒狀態
調用start()方法,線程進入就緒狀態,但并不意味著線程就立即執行,只是說明此線程已經做好準備,隨時等待CPU調度執行。
阻塞狀態
多個線程同時競爭一個獨占鎖,其他未搶到鎖的線程,就進入阻塞狀態被放置到鎖池中,直到獲取到鎖,進入就緒狀態
等待狀態
該線程需要等待其他線程做出一些特定動作,通知或者是中斷,等待其被其他線程喚醒,像CountDownLatch就可以等待一個或者幾個線程結束。
超時等待狀態
和等待狀態不同的是,它可以在指定的時間自行的返回,sheep(long)函數就會讓線程進入超時等待狀態,時間到了才會轉入就緒狀態。
運行狀態(Running)
CPU調度處于就緒狀態的線程時,這個線程才真正執行,進入運行狀態。
終止狀態
線程正常執行完畢后或提前強制性終止或出現異常,線程就要銷毀,釋放資源。
Java創建線程的兩種方式
繼承Thread類
public class ThreadDemo1 extendsThread {
@Overridepublic voidrun(){for (int i = 0; i < 10; i++) {
System.out.println("當前執行的線程是" +Thread.currentThread().getName());
}
}public static voidmain(String[] args) {
ThreadDemo1 threadDemo1= newThreadDemo1();
ThreadDemo1 threadDemo2= newThreadDemo1();
threadDemo1.start();
threadDemo2.start();
}
}
執行結果是不確定的
實現Runnable
public class ThreadDemo2 implementsRunnable {
@Overridepublic voidrun() {for (int i = 0; i < 10; i++) {for (int j = 0;j < 1000; ++j){
System.out.println(i+ "當前執行的線程是" +Thread.currentThread().getName());
}
}
}public static voidmain(String[] args) {
ThreadDemo2 threadDemo1= newThreadDemo2();
ThreadDemo2 threadDemo2= newThreadDemo2();
Thread thread1= newThread(threadDemo1);
Thread thread2= newThread(threadDemo2);
thread1.start();
thread2.start();
System.out.println("當前線程是===>" +Thread.currentThread().getName());
}
}
主線程的名字為main,非主線程的名字是由虛擬機來指定的,同時,我們也可以為線程指定具體的名稱。
我們保證每個線程都能正常啟動,并不意味著它會按順序的執行,因為調度程序是無法保證它的執行次序的,同時,run()函數結束時,意味著該線程的任務完成了。
注意:調用線程要調用start,如果調用run,那僅僅是簡單的對象調用。
線程的方法調用
獲取線程基本信息
public classThreadDemo6 {public static voidmain(String[] args) {
Thread thread= newThread(){
@Overridepublic voidrun(){/*獲取線程唯一id標識*/
long id = this.getId();
System.out.println("thread的ID==>" +id);/*獲取線程名字*/String name= this.getName();
System.out.println("thread的名字==>" +name);/*獲取線程的優先級 默認5 1-10*/
int priority = this.getPriority();
System.out.println("thread的優先等級==>" +priority);/*查看當前線程是否為守護線程*/
boolean isDaemon = this.isDaemon();
System.out.println("thread是否為守護線程==>" +isDaemon);/*查看線程是否被中斷*/
boolean isInterrupted = this.isInterrupted();
System.out.println("thread是否被中斷==>" +isInterrupted);
}
};
thread.start();
}
}
執行結果
thread的ID==>11thread的名字==>Thread-0thread的優先等級==>5thread是否為守護線程==>falsethread是否被中斷==>false
Thread.yield()
public class ThreadDemo1 implementsRunnable {protected int countDown = 10;private static int taskCount = 0;private final int id = taskCount++;publicThreadDemo1(){}public ThreadDemo1(intcountDown){this.countDown =countDown;
}publicString status(){return "#" + id + "(" + (countDown > 0 ? countDown : "stop!") + ")";
}
@Overridepublic voidrun() {while (countDown-- > 0){
System.out.println(status()+ " ");
Thread.yield();
}
}public static voidmain(String[] args) {for (int i = 0; i < 3; i++){new Thread(newThreadDemo1()).start();
}
}
}
#0(9)#0(8)#0(7)#0(6)#0(5)#0(4)#0(3)#0(2)#0(1)#0(stop!)
#1(9)#1(8)#1(7)#1(6)#1(5)#1(4)#1(3)#1(2)#1(1)#1(stop!)
#2(9)#2(8)#2(7)#2(6)#2(5)#2(4)#2(3)#2(2)#2(1)#2(stop!)
這個是一個倒計時的任務,對Thread.yield()調用是對線程調度器的一種建議,它在聲明“我已經執行完生命周期中最重要的部分了,此刻正是切換給其他任務執行一段時間的大好時機”,說白就是自己按暫停鍵,讓出自己CPU的使用權限,轉為就緒狀態,至于下一次什么時候能獲得CPU調度就不一定了,有時很快,有時得等上一會。
Thread.sleep
public class ThreadDemo1 implementsRunnable {protected int countDown = 10;private static int taskCount = 0;private final int id = taskCount++;publicThreadDemo1(){}public ThreadDemo1(intcountDown){this.countDown =countDown;
}publicString status(){return "#" + id + "(" + (countDown > 0 ? countDown : "stop!") + ")";
}
@Overridepublic voidrun() {try{while (countDown-- > 0){
System.out.println(status());
Thread.sleep(1000);
}
}catch(InterruptedException e) {
e.printStackTrace();
}
}public static voidmain(String[] args) {for (int i = 0; i < 3; i++){new Thread(newThreadDemo1()).start();
}
}
}
Thread.sleep(long)將使“正在執行的任務“中止執行給定的時間(暫停執行)并且讓出CPU使用權,這個語句相當于說在接下來的1秒內,你都不要叫我,我想睡一會,1秒睡眠時間過后,它自動轉為就緒狀態,但CPU不一定馬上執行這個睡醒的線程,這要取決于是否搶到CPU時間片段。值得注意的是如果sleep和yield上下文被加鎖了,它們依然使用鎖,不會去釋放。而sleep與yield最大的不同是,yield不會讓線程進入等待狀態,只是把線程轉為就緒狀態,并把CPU執行機會讓步給優先級相同或者更高的線程,而sleep能控制具體交出CPU的使用時間。
Thread.currentThread()
public class ThreadDemo2 extendsThread {static{
System.out.println("靜態塊執行的線程===>" +Thread.currentThread().getName());
}
{
System.out.println("非靜態塊執行的線程是====>" +Thread.currentThread().getName());
System.out.println("this.getName()1=====>" + this.getName());
}publicThreadDemo2(){
System.out.println("構造方法內執行的線程====>" +Thread.currentThread().getName());
System.out.println("this.getName()2=====>" + this.getName());
}
@Overridepublic voidrun() {
System.out.println("當前執行的線程為====>" +Thread.currentThread().getName());
System.out.println("this.getName()3=====>" + this.getName());
}public static voidmain(String[] args) {
ThreadDemo2 threadDemo2= newThreadDemo2();
threadDemo2.start();
}
}
執行結果
靜態塊執行的線程===>main
非靜態塊執行的線程是====>mainthis.getName()1=====>Thread-0構造方法內執行的線程====>mainthis.getName()2=====>Thread-0當前執行的線程為====>Thread-0
this.getName()3=====>Thread-0
currentThread返回的是當前正在執行線程對象的引用,它與this.getName()有明顯的不同,執行靜態塊,非靜態塊,構造方法的線程是main,而非ThreadDemo2,在執行run()方法的才是實例化的線程threadDemo2。所以在當前執行的Thread未必就是Thread本身。
isAlive()
public class ThreadDemo3 extendsThread {
@Overridepublic voidrun(){
System.out.println("執行執行====" + this.isAlive());
}public static voidmain(String[] args) {
ThreadDemo3 threadDemo3= newThreadDemo3();
System.out.println("begin===>" +threadDemo3.isAlive());
threadDemo3.start();
System.out.println("end==>" +threadDemo3.isAlive());
}
}
begin===>falseend==>true執行執行====true
isAlive()檢測線程是否處于活動狀態,活動狀態返回true
setPriority()
優先級設定,優先級高的線程越容易獲取CPU使用權,
public classThreadDemo4 {public static voidmain(String[] args) {for (int i = 0; i < 5; ++i){
Thread1 thread1= newThread1();
thread1.setPriority(6);
Thread2 thread2= newThread2();
thread2.setPriority(4);
thread2.start();
thread1.start();
}
}
}class Thread1 extendsThread{
@Overridepublic voidrun(){for (int i = 0; i < 100000; ++i){
System.out.println("+++++++++++++");
}
}
}class Thread2 extendsThread{
@Overridepublic voidrun(){for (int i = 0; i < 100000; ++i){
System.out.println("--------------");
}
}
}
執行結果
+++++++++++++
+++++++++++++
+++++++++++++
+++++++++++++
+++++++++++++
+++++++++++++
+++++++++++++
+++++++++++++
...
CPU會將資源盡量讓給優先級高的線程
setDaemon()
守護線程,也有人叫后天線程,我們創建出來的線程默認都是前臺線程,在使用上來說,守護線程和前臺線程是沒啥區別,區別在于進程結束,當一個進程中的所有前臺線程都結束時,無論這個進程中的守護線程是否還在運行都要強制將他們結束。也就是說前臺線程都結束了,守護線程也會自動銷毀,它是為其他線程提供便利而存在的。
/*rose與jack*/
public classThreadDemo5 {public static voidmain(String[] args) {
Rose rose= newRose();
Jack jack= newJack();/*設置為守護線程必須在線程未啟動之前*/jack.setDaemon(true);
rose.start();
jack.start();
}
}class Rose extendsThread{
@Overridepublic voidrun(){for (int i = 0; i < 5; ++i){
System.out.println("rose: let me go!");try{
Thread.sleep(1000);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("成功跳水");
}
}class Jack extendsThread{
@Overridepublic voidrun(){while (true){
System.out.println("jack:you jump! i jump!");try{
Thread.sleep(1000);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}
執行結果
rose: let me go!jack:you jump! i jump!rose: let me go!jack:you jump! i jump!rose: let me go!jack:you jump! i jump!rose: let me go!jack:you jump! i jump!rose: let me go!jack:you jump! i jump!成功跳水
jack守護著rose,jack是守護線程,當rose跳水后,jack認為自己也沒有活著的必要了,也自己銷毀了,但注意一點是這當中還有一個第三者main,需要main也運行完jack線程才會銷毀。
join()
這個方法可以協調多個線程同步運行,多線程運行本身是設計異步運行的,但在程序運行業務中,有可能線程A的計算需要線程B的返回結果,這就需要他們執行各自任務時要有先后,join就需要協調這些線程同步運行。
public classThreadDemo6 {private static boolean isFinish = false;public static voidmain(String[] args) {
Thread download= newThread(){
@Overridepublic voidrun(){
System.out.println("下載圖片中.....");for (int i = 1; i <= 100; ++i){
System.out.println("下載進度" + i + "%");try{
Thread.sleep(1000);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("圖片下載完畢");
isFinish= true;
}
};
Thread show= newThread(){
@Overridepublic voidrun(){
System.out.println("開始顯示圖片...");try{
download.join();
}catch(InterruptedException e) {
e.printStackTrace();
}if (!isFinish){throw new RuntimeException("圖片下載出錯");
}
System.out.println("圖片正常展示。。。");
}
};
download.start();
show.start();
}
}
執行結果
下載圖片中.....
開始顯示圖片...
下載進度1%下載進度2%...
下載進度100%圖片下載完畢
圖片正常展示。。。
show調用join會使show無限阻塞,直到down線程銷毀為止,它和sleep最大的區別是join會釋放鎖,而sleep不會。
涉及到jmm內存模型,線程安全等,后面在介紹
總結
以上是生活随笔為你收集整理的java 多线程的使用_Java的多线程1:线程的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: eclipse java参数类型_JAV
- 下一篇: jmeter测试java_使用JMete