国产片侵犯亲女视频播放_亚洲精品二区_在线免费国产视频_欧美精品一区二区三区在线_少妇久久久_在线观看av不卡

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術|正則表達式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務器之家 - 編程語言 - Java教程 - 淺談多線程_讓程序更高效的運行

淺談多線程_讓程序更高效的運行

2021-01-19 10:12romanjoy Java教程

下面小編就為大家帶來一篇淺談多線程_讓程序更高效的運行。小編覺得挺不錯的,現在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

java thread 的一些認識:

java是搶占式線程,一個線程就是進程中單一的順序控制流,單個進程可以擁有多個并發任務,其底層是切分cpu時間,多線程和多任務往往是使用多處理器系統的最合理方式

進程可以看作一個程序或者一個應用;線程是進程中執行的一個任務,多個線程可以共享資源

一個java 應用從main 方法開始運行,main 運行在一個線程內,也被稱為 “主線程”,runnable也可以理解為task (任務)

jvm啟動后,會創建一些守護線程來進行自身的常規管理(垃圾回收,終結處理),以及一個運行main函數的主線程

隨著硬件水平的提高,多線程能使系統的運行效率得到大幅度的提高,同時異步操作也增加復雜度和各種并發問題

淺談多線程_讓程序更高效的運行

■ 線程 vs 進程

在一個已有進程中創建一個新線程比創建一個新進程快的多

終止一個線程比終止一個進程快的多

同一個進程內線程間切換比進程間切換更快

線程提供了不同的執行程序間通信的效率,同一個進程中的線程共享同一進程內存和文件,無序調用內核就可以互相通信,而進程間通信必須通過內核

■ 同步和異步

同步方法一旦開始,調用者必須等到方法調用返回之后,才能繼續后續行為

無先后順序,一旦開始,方法調用便立即返回,調用者就可以繼續后續行為,一般為另一個線程執行

■ 阻塞和非阻塞

當一個線程占用臨界區資源,其他線程也想要使用該資源就必須等待,等待會導致線程的掛起,也就是阻塞(線程變成阻塞狀態)。

此時若占用資源的線程一直不愿意釋放資源,那么其他所有阻塞在該臨界區的線程都會被掛起,變成阻塞狀態,不能正常工作,直到占用線程釋放資源

非阻塞強調沒有一個線程可以妨礙其他線程執行,所有線程都會嘗試去做下一步工作

■ 臨界資源與臨界區

一般指的是公共共享資源,即可以被多個線程共享使用。但同一時間只能由一個線程去訪問和操作臨界區的資源,一旦臨界區資源被一個線程占用,其他線程也想要使用該資源就必須等待,

就好比好多人想上大號,但只有一個坑,一個人占了坑,其他人就得排隊等待嘍

臨界區可以認為是一段代碼,線程會在該端代碼中訪問共享資源,因此臨界區的界定標準就是是否訪問共享(臨界)資源(有點類似形成閉包的概念);一次只允許有一個程序(進程/線程)在該臨界區中

■ 類定義

 

?
1
2
3
4
5
6
7
8
public class thread implements runnable {
  /* make sure registernatives is the first thing <clinit> does.
    初始化時調用 java 本地方法,實現了runnable接口
  */
 private static native void registernatives();
 static {
  registernatives();
 }

■ 構造器

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
/**
 * 默認構造器
 * 其中name規則為 "thread-" + nextthreadnum()
 */
public thread() {
 init(null, null, "thread-" + nextthreadnum(), 0);
}
/**
 * 創建一個指定runnable的線程
 * 其中name規則為 "thread-" + nextthreadnum()
 */
public thread(runnable target) {
 init(null, target, "thread-" + nextthreadnum(), 0);
}
/**
 * 創建一個指定所屬線程組和runnable的線程
 * 其中name規則為 "thread-" + nextthreadnum()
 */
public thread(threadgroup group, runnable target) {
 init(group, target, "thread-" + nextthreadnum(), 0);
}
/**
 * 創建一個指定name線程
 */
public thread(string name) {
 init(null, null, name, 0);
}
/**
 * 創建一個指定所屬線程組和name的線程
 */
public thread(threadgroup group, string name) {
 init(group, null, name, 0);
}
/**
 * 創建一個指定runnable和name的線程
 */
public thread(runnable target, string name) {
 init(null, target, name, 0);
}
/**
 * allocates a new {@code thread} object so that it has {@code target}
 * as its run object, has the specified {@code name} as its name,
 * and belongs to the thread group referred to by {@code group}.
 *  創建一個新的thread對象,同時滿足以下條件:
 *   1.該線程擁有一個指定的runnable對象用于方法執行
 *   2.該線程具有一個指定的名稱
 *   3.該線程屬于一個指定的線程組threadgroup
 * <p>if there is a security manager, its
 * {@link securitymanager#checkaccess(threadgroup) checkaccess}
 * method is invoked with the threadgroup as its argument.
 *  若這里有個安全管理器,則threadgroup將調用checkaccess方法進而觸發securitymanager的checkaccess方法
 * <p>in addition, its {@code checkpermission} method is invoked with
 * the {@code runtimepermission("enablecontextclassloaderoverride")}
 * permission when invoked directly or indirectly by the constructor of a subclass which
 * overrides the {@code getcontextclassloader} or {@code setcontextclassloader} methods.
 *  當enablecontextclassloaderoverride被開啟時,checkpermission將被重寫子類直接或間接地調用
 * <p>the priority of the newly created thread is set equal to the
 * priority of the thread creating it, that is, the currently running
 * thread. the method {@linkplain #setpriority setpriority} may be
 * used to change the priority to a new value.
 *  新創建的thread的優先級等同于創建它的線程的優先級,調用setpriority會變更其優先級
 * <p>the newly created thread is initially marked as being a daemon
 * thread if and only if the thread creating it is currently marked
 * as a daemon thread. the method {@linkplain #setdaemon setdaemon}
 * may be used to change whether or not a thread is a daemon.
 *  當且僅當線程創建時被顯示地標記為守護線程,新創建的線程才會被初始化為一個守護線程
 *  setdaemon方法可以設置當前線程是否為守護線程
 */
public thread(threadgroup group, runnable target, string name) {
 init(group, target, name, 0);
}
/**
 * allocates a new {@code thread} object so that it has {@code target} as its run object,
 * has the specified {@code name} as its name, and belongs to the thread group referred to
 * by {@code group}, and has the specified <i>stack size</i>.
 *  創建一個新的thread對象,同時滿足以下條件:
 *   1.該線程擁有一個指定的runnable對象用于方法執行
 *   2.該線程具有一個指定的名稱
 *   3.該線程屬于一個指定的線程組threadgroup
 *   4.該線程擁有一個指定的棧容量
 * <p>this constructor is identical to {@link #thread(threadgroup,runnable,string)}
 * with the exception of the fact that it allows the thread stack size to be specified.
 * the stack size is the approximate number of bytes of address space that the virtual machine
 * is to allocate for this thread's stack. <b>the effect of the {@code stacksize} parameter,
 * if any, is highly platform dependent.</b>
 *  棧容量指的是jvm分配給該線程的棧的地址(內存)空間大小,這個參數的效果高度依賴于jvm運行平臺
 * <p>on some platforms, specifying a higher value for the {@code stacksize} parameter may allow
 * a thread to achieve greater recursion depth before throwing a {@link stackoverflowerror}.
 * similarly, specifying a lower value may allow a greater number of threads to exist
 * concurrently without throwing an {@link outofmemoryerror} (or other internal error).
 * the details of the relationship between the value of the <tt>stacksize</tt> parameter
 * and the maximum recursion depth and concurrency level are platform-dependent.
 * <b>on some platforms, the value of the {@code stacksize} parameter
 * may have no effect whatsoever.</b>
 *  在一些平臺上,棧容量越高,(會在棧溢出之前)允許線程完成更深的遞歸(換句話說就是棧空間更深)
 *  同理,若棧容量越小,(在拋出內存溢出之前)允許同時存在更多的線程數
 *  對于棧容量、最大遞歸深度和并發水平之間的關系依賴于平臺
 * <p>the virtual machine is free to treat the {@code stacksize} parameter as a suggestion.
 * if the specified value is unreasonably low for the platform,the virtual machine may instead
 * use some platform-specific minimum value; if the specified value is unreasonably high,
 * the virtual machine may instead use some platform-specific maximum.
 * likewise, the virtual machine is free to round the specified value up or down as it sees fit
 * (or to ignore it completely).
 *  jvm會將指定的棧容量作為一個參考依據,但當小于平臺最小值時會直接使用最小值,最大值同理
 *  同樣,jvm會動態調整棧空間的大小以適應程序的運行或者甚至直接就忽視該值的設置
 * <p><i>due to the platform-dependent nature of the behavior of this constructor, extreme care
 * should be exercised in its use.the thread stack size necessary to perform a given computation
 * will likely vary from one jre implementation to another. in light of this variation,
 * careful tuning of the stack size parameter may be required,and the tuning may need to
 * be repeated for each jre implementation on which an application is to run.</i>
 *  簡單總結一下就是:這個值嚴重依賴平臺,所以要謹慎使用,多做測試驗證
 * @param group
 *   the thread group. if {@code null} and there is a security
 *   manager, the group is determined by {@linkplain
 *   securitymanager#getthreadgroup securitymanager.getthreadgroup()}.
 *   if there is not a security manager or {@code
 *   securitymanager.getthreadgroup()} returns {@code null}, the group
 *   is set to the current thread's thread group.
 *    當線程組為null同時有個安全管理器,該線程組由securitymanager.getthreadgroup()決定
 *    當沒有安全管理器或getthreadgroup為空,該線程組即為創建該線程的線程所屬的線程組
 * @param target
 *   the object whose {@code run} method is invoked when this thread
 *   is started. if {@code null}, this thread's run method is invoked.
 *    若該值為null,將直接調用該線程的run方法(等同于一個空方法)
 * @param name
 *   the name of the new thread
 * @param stacksize
 *   the desired stack size for the new thread, or zero to indicate
 *   that this parameter is to be ignored.
 *    當棧容量被設置為0時,jvm就會忽略該值的設置
 * @throws securityexception
 *   if the current thread cannot create a thread in the specified thread group
 *    如果當前線程在一個指定的線程組中不能創建一個新的線程時將拋出 安全異常
 * @since 1.4
 */
public thread(threadgroup group, runnable target, string name,long stacksize) {
 init(group, target, name, stacksize);
}

■ 重要變量

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
//線程名,用char來保存(string底層實現就是char)
private char  name[];
//線程優先級
private int   priority;
//不明覺厲
private thread  threadq;
//不明覺厲
private long  eetop;
/* whether or not to single_step this thread. 不明覺厲*/
private boolean  single_step;
/* whether or not the thread is a daemon thread. 是否是守護線程,默認非守護線程*/
private boolean  daemon = false;
/* jvm state. 是否一出生就領便當,默認false*/
private boolean  stillborn = false;
/* what will be run. thread的run方法最終會調用target的run方法*/
private runnable target;
/* the group of this thread. 當前線程的所屬線程組*/
private threadgroup group;
/* the context classloader for this thread 當前線程的classloader*/
private classloader contextclassloader;
/* the inherited accesscontrolcontext of this thread 當前線程繼承的accesscontrolcontext*/
private accesscontrolcontext inheritedaccesscontrolcontext;
/* for autonumbering anonymous threads. 給匿名線程自動編號,并按編號起名字*/
private static int threadinitnumber;
/* threadlocal values pertaining to this thread. this map is maintained by the threadlocal class.
 * 當前線程附屬的threadlocal,而threadlocalmap會被threadlocal維護(threadlocal會專門分析)
 */
threadlocal.threadlocalmap threadlocals = null;
/*
 * inheritablethreadlocal values pertaining to this thread. this map is
 * maintained by the inheritablethreadlocal class.
 * 主要作用:為子線程提供從父線程那里繼承的值
 * 在創建子線程時,子線程會接收所有可繼承的線程局部變量的初始值,以獲得父線程所具有的值
 * 創建一個線程時如果保存了所有 inheritablethreadlocal 對象的值,那么這些值也將自動傳遞給子線程
 * 如果一個子線程調用 inheritablethreadlocal 的 get() ,那么它將與它的父線程看到同一個對象
 */
 threadlocal.threadlocalmap inheritablethreadlocals = null;
/*
 * the requested stack size for this thread, or 0 if the creator did not specify a stack size.
 * it is up to the vm to do whatever it likes with this number; some vms will ignore it.
 * 棧容量:當設置為0時,jvm會忽略該值;該值嚴重依賴于jvm平臺,有些vm甚至會直接忽視該值
 * 該值越大,線程棧空間變大,允許的并發線程數就越少;該值越小,線程棧空間變小,允許的并發線程數就越多
 */
private long stacksize;
/* jvm-private state that persists after native thread termination.*/
private long nativeparkeventpointer;
/* thread id. 每個線程都有專屬id,但名字可能重復*/
private long tid;
/* for generating thread id 用于id生成,每次+1*/
private static long threadseqnumber;
/*
 * java thread status for tools,initialized to indicate thread 'not yet started'
 * 線程狀態 0僅表示已創建
 */
private volatile int threadstatus = 0;
/**
 * the argument supplied to the current call to java.util.concurrent.locks.locksupport.park.
 * set by (private) java.util.concurrent.locks.locksupport.setblocker
 * accessed using java.util.concurrent.locks.locksupport.getblocker
 * 主要是提供給 java.util.concurrent.locks.locksupport該類使用
 */
volatile object parkblocker;
/* the object in which this thread is blocked in an interruptible i/o operation, if any.
 * the blocker's interrupt method should be invoked after setting this thread's interrupt status.
 * 中斷阻塞器:當線程發生io中斷時,需要在線程被設置為中斷狀態后調用該對象的interrupt方法
 */
private volatile interruptible blocker;
//阻塞器鎖,主要用于處理阻塞情況
private final object blockerlock = new object();
 /* the minimum priority that a thread can have. 最小優先級*/
public final static int min_priority = 1;
/* the default priority that is assigned to a thread. 默認優先級*/
public final static int norm_priority = 5;
/* for generating thread id 最大優先級*/
public final static int max_priority = 10;
/* 用于存儲堆棧信息 默認是個空的數組*/
private static final stacktraceelement[] empty_stack_trace = new stacktraceelement[0];
private static final runtimepermission subclass_implementation_permission =
   new runtimepermission("enablecontextclassloaderoverride");
// null unless explicitly set 線程異常處理器,只對當前線程有效
private volatile uncaughtexceptionhandler uncaughtexceptionhandler;
// null unless explicitly set 默認線程異常處理器,對所有線程有效
private static volatile uncaughtexceptionhandler defaultuncaughtexceptionhandler;

■ 本地方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
/*
 * make sure registernatives is the first thing <clinit> does.
 * 確保clinit最先調用該方法:所有該方法是類中的最靠前的一個靜態方法
 * clinit:在jvm第一次加載class文件時調用,用于靜態變量初始化語句和靜態塊的執行
 * 所有的類變量初始化語句和類型的靜態初始化語句都被java編譯器收集到該方法中
 *
 * registernatives方法被native修飾,即是本地方法,將由c/c++去完成,并被編譯成了.dll,供java調用
 * 其主要作用是將c/c++中的方法映射到java中的native方法,實現方法命名的解耦
 */
private static native void registernatives();
static {
 registernatives();
}
/** 主動讓出cpu資源,當時可能又立即搶到資源 **/
public static native void yield();
/** 休眠一段時間,讓出資源但是并不會釋放對象鎖 **/
public static native void sleep(long millis) throws interruptedexception;
/** 檢查 線程是否存活 **/
public final native boolean isalive();
/** 檢查線程是否中斷 isinterrupted() 內部使用 **/
private native boolean isinterrupted(boolean clearinterrupted);
/** 返回當前執行線程 **/
public static native thread currentthread();
public static native boolean holdslock(object obj);
private native void start0();
private native void setpriority0(int newpriority);
private native void stop0(object o);
private native void suspend0();
private native void resume0();
private native void interrupt0();
private native void setnativename(string name);

■ 線程初始化

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
/**
 * initializes a thread.
 *  初始化一個線程
 * @param g the thread group
 * @param target the object whose run() method gets called
 * @param name the name of the new thread
 * @param stacksize the desired stack size for the new thread, or
 *  zero to indicate that this parameter is to be ignored.
 */
private void init(threadgroup g, runnable target, string name,long stacksize) {
 if (name == null) {
  throw new nullpointerexception("name cannot be null");
 }
 //返回當前線程,即創建該hread的線程 currentthread是個本地方法
 thread parent = currentthread();
 //安全管理器根據java安全策略文件決定將哪組權限授予類
 //如果想讓應用使用安全管理器和安全策略,可在啟動jvm時設定-djava.security.manager選項
 //還可以同時指定安全策略文件
 //如果在應用中啟用了java安全管理器,卻沒有指定安全策略文件,那么java安全管理器將使用默認的安全策略
 //它們是由位于目錄$java_home/jre/lib/security中的java.policy定義的
 securitymanager security = system.getsecuritymanager();
 if (g == null) {
  /* determine if it's an applet or not */
  /* if there is a security manager, ask the security manager what to do. */
  if (security != null) {
   g = security.getthreadgroup();
  }
  /* if the security doesn't have a strong opinion of the matter use the parent thread group. */
  if (g == null) {
   g = parent.getthreadgroup();
  }
 }
 /* checkaccess regardless of whether or not threadgroup is explicitly passed in. */
 //判斷當前運行線程是否有變更其線程組的權限
 g.checkaccess();
 if (security != null) {
  if (isccloverridden(getclass())) {
   security.checkpermission(subclass_implementation_permission);
  }
 }
 //新建線程數量計數+1 或者說未就緒線程數+1==> nunstartedthreads++;
 g.addunstarted();
 this.group = g;
 this.daemon = parent.isdaemon();//若當前運行線程是守護線程,新建線程也是守護線程
 this.priority = parent.getpriority();//默認使用當前運行線程的優先級
 this.name = name.tochararray();
 //設置contextclassloader
 if (security == null || isccloverridden(parent.getclass()))
  this.contextclassloader = parent.getcontextclassloader();
 else
  this.contextclassloader = parent.contextclassloader;
 this.inheritedaccesscontrolcontext = accesscontroller.getcontext();
 this.target = target;
 setpriority(priority);//若有指定的優先級,使用指定的優先級
 if (parent.inheritablethreadlocals != null)
  this.inheritablethreadlocals =
   threadlocal.createinheritedmap(parent.inheritablethreadlocals);
 /* stash the specified stack size in case the vm cares */
 this.stacksize = stacksize;
 /* set thread id 線程安全,序列號每次同步+1*/
 tid = nextthreadid();
}
private static synchronized long nextthreadid() {
 return ++threadseqnumber;
}

■ start 方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/**
 * causes this thread to begin execution; the java virtual machine
 * calls the <code>run</code> method of this thread.
 *  線程進入就緒態,隨后jvm將會調用這個線程run方法
 *  當獲取到cpu時間片時,會立即執行run方法,此時線程會直接變成運行態
 * <p>
 * the result is that two threads are running concurrently: the
 * current thread (which returns from the call to the
 * <code>start</code> method) and the other thread (which executes its
 * <code>run</code> method).
 * <p>
 * it is never legal to start a thread more than once.
 * in particular, a thread may not be restarted once it has completed execution.
 *  一個線程只能被start一次,特別是線程不會在執行完畢后重新start
 *  當線程已經start了,再次執行會拋出illegalthreadstateexception異常
 * @exception illegalthreadstateexception if the thread was already started.
 * @see  #run()
 * @see  #stop()
 */
public synchronized void start() {
 /**
  * this method is not invoked for the main method thread or "system"
  * group threads created/set up by the vm. any new functionality added
  * to this method in the future may have to also be added to the vm.
  * 該方法不會被主線程或系統線程組調用,若未來有新增功能,也會被添加到vm中
  * a zero status value corresponds to state "new".
  * 0對應"已創建"狀態 -> 用常量或枚舉標識多好
  */
 if (threadstatus != 0)
  throw new illegalthreadstateexception();
 /* notify the group that this thread is about to be started
  * so that it can be added to the group's list of threads
  * and the group's unstarted count can be decremented. */
 //通知所屬線程組該線程已經是就緒狀態,因而可以被添加到該線程組中
 //同時線程組的未就緒線程數需要-1,對應init中的+1
 group.add(this);
 boolean started = false;
 try {
  //調用本地方法,將內存中的線程狀態變更為就緒態
  //同時jvm會立即調用run方法,獲取到cpu之后,線程變成運行態并立即執行run方法
  start0();
  started = true;//標記為已開啟
 } finally {
  try {
   if (!started) {
    group.threadstartfailed(this);//如果變更失敗,要回滾線程和線程組狀態
   }
  } catch (throwable ignore) {
   /* do nothing. if start0 threw a throwable then
     it will be passed up the call stack */
   //如果start0出錯,會被調用棧直接通過
  }
 }
}
-------------
//start之后會立即調用run方法
thread t = new thread( new runnable() {
 @override
 public void run() {
  system.out.println(thread.currentthread().getname());
 }
},"roman");
t.start(); //roman

■ run 方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
 * if this thread was constructed using a separate <code>runnable</code> run object,
 * then that <code>runnable</code> object's <code>run</code> method is called;
 * otherwise, this method does nothing and returns.
 * subclasses of <code>thread</code> should override this method.
 * 若thread初始化時有指定runnable就執行其的run方法,否則donothing
 * 該方法必須被子類實現
 */
@override
public void run() {
 if (target != null) {
  target.run();
 }
}

■ isalive 方法

?
1
2
3
4
5
6
7
8
9
/**
 * tests if this thread is alive. a thread is alive if it has
 * been started and has not yet died.
 *  測試線程是否處于活動狀態
 *  活動狀態:線程處于正在運行或者準備開始運行狀態
 * @return <code>true</code> if this thread is alive;
 *   <code>false</code> otherwise.
 */
public final native boolean isalive();

? 線程運行 : 模擬電梯運行類

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
public class liftoff implements runnable {
 private int countdown = 10; //電梯階層
// private static int taskcount = 0;
// private final int id = taskcount++;
 
 public liftoff(){
 }
 
 // syn countdown
 private synchronized int getcountdown(){
  --countdown;
  return countdown;
 }
 
 // 獲取電梯狀態
 public string status() {
  return thread.currentthread().tostring()+ "("+
    (countdown > 0? countdown: "liftoff!") + "),";
 }
 
 @override
 public void run(){
  while (getcountdown() >0){
   system.out.println(status());
   thread.yield();
  }
 }
 
 public static void main(string[] args) {
  // thread's start()
  thread thread = new thread(new liftoff());
  thread.start(); // 調用 run()
  system.out.println("================waiting for liftoff...===========================");
 }
 
}

線程都會有自己的名字

獲取線程對象的方法: thread.currentthread()

目標 run() 結束后線程完成

jvm線程調度程序決定實際運行哪個處于可運行狀態的線程

使用線程池執行處理任務

線程狀態流程圖:

淺談多線程_讓程序更高效的運行

■ sleep 方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
/**
 * causes the currently executing thread to sleep (temporarily cease execution)
 * for the specified number of milliseconds plus the specified number of nanoseconds,
 * subject to the precision and accuracy of system timers and schedulers.
 * the thread does not lose ownership of any monitors.
 *  使線程睡眠一段毫秒時間,但線程并不會丟失已有的任何監視器
 */
public static void sleep(long millis, int nanos) throws interruptedexception {
 if (millis < 0) {
  throw new illegalargumentexception("timeout value is negative");
 }
 if (nanos < 0 || nanos > 999999) {
  throw new illegalargumentexception("nanosecond timeout value out of range");
 }
 //換算用
 if (nanos >= 500000 || (nanos != 0 && millis == 0)) {
  millis++;
 }
 sleep(millis);
}
/** 我們一般會直接調用native方法,這或許是我們主動使用的最多次的native方法了 **/
public static native void sleep(long millis) throws interruptedexception;

■ yield 方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/**
 * a hint to the scheduler that the current thread is willing to yield
 * its current use of a processor. the scheduler is free to ignore this hint.
 * 暗示線程調度器當前線程將釋放自己當前占用的cpu資源
 * 線程調度器會自由選擇是否忽視此暗示
 * <p> yield is a heuristic attempt to improve relative progression
 * between threads that would otherwise over-utilise a cpu. its use
 * should be combined with detailed profiling and benchmarking to
 * ensure that it actually has the desired effect.
 * 該方法會放棄當前的cpu資源,將它讓給其他的任務去占用cpu執行時間
 * 但放棄的時間不確定,可能剛剛放棄又獲得cpu時間片
 * <p> it is rarely appropriate to use this method. it may be useful
 * for debugging or testing purposes, where it may help to reproduce
 * bugs due to race conditions. it may also be useful when designing
 * concurrency control constructs such as the ones in the
 * {@link java.util.concurrent.locks} package.
 * 該方法的適合使用場景比較少,主要用于debug,比如lock包設計
 */
public static native void yield();

■ interrupt 方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
 * interrupts this thread.
 *  中斷一個線程
 * <p> unless the current thread is interrupting itself, which is always permitted,
 * the {@link #checkaccess() checkaccess} method of this thread is invoked,
 * which may cause a {@link securityexception} to be thrown.
 *  如果當前線程不是被自己中斷,可能會拋出securityexception異常
 * <p> if this thread is blocked in an invocation of the {@link object#wait() wait()},
 * {@link object#wait(long) wait(long)}, or {@link object#wait(long, int) wait(long, int)}
 * methods of the {@link object} class, or of the {@link #join()}, {@link #join(long)}, {@link
 * #join(long, int)}, {@link #sleep(long)}, or {@link #sleep(long, int)},methods of this class,
 * then its interrupt status will be cleared and it will receive an {@link interruptedexception}.
 *  若當前線程已被object.wait()方法、thread的join()或sleep方法阻塞,
 *  則調用該中斷方法會拋出interruptedexception同時中斷狀態會被清除
 * <p> if this thread is blocked in an i/o operation upon an {@link
 * java.nio.channels.interruptiblechannel </code>interruptible channel<code>}
 * then the channel will be closed, the thread's interrupt status will be set,
 * and the thread will receive a {@link java.nio.channels.closedbyinterruptexception}.
 *  若當前線程在interruptiblechannel上發生io阻塞,該通道要被關閉并將線程狀態設置為中斷同時拋出
 * closedbyinterruptexception異常
 * <p> if this thread is blocked in a {@link java.nio.channels.selector} then the thread's
 * interrupt status will be set and it will return immediately from the selection operation,
 * possibly with a non-zero value, just as if the selector's {@link
 * java.nio.channels.selector#wakeup wakeup} method were invoked.
 *  若該線程被選擇器阻塞,將線程狀態設置為中斷同時從選取方法中立即返回
 *  該選取方法通常會返回一個非0值,當wakeup方法正好被調用時
 * <p> if none of the previous conditions hold then this thread's interrupt status will be set. </p>
 *  非上述情況都會將線程狀態設置為中斷
 * <p> interrupting a thread that is not alive need not have any effect.
 *  中斷一個非活線程不會有啥影響
 * @throws securityexception if the current thread cannot modify this thread
 * @revised 6.0
 * @spec jsr-51
 */
public void interrupt() {
 if (this != thread.currentthread())
  checkaccess();
 synchronized (blockerlock) {
  interruptible b = blocker;
  if (b != null) {
   // just to set the interrupt flag
   // 調用interrupt方法僅僅是在當前線程中打了一個停止的標記,并不是真的停止線程!
   interrupt0();  
   b.interrupt(this);
   return;
  }
 }
 interrupt0();
}

■ daemon

分類:在java中分成兩種線程:用戶線程和守護線程

特性:當進程中不存在非守護線程時,則全部的守護線程會自動化銷毀

應用: jvm在啟動后會生成一系列守護線程,最有名的當屬gc(垃圾回收器)

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
thread t2 = new thread(new runnable() {
 @override
 public void run() {
  system.out.println("守護線程運行了");
  for (int i = 0; i < 500000;i++){
   system.out.println("守護線程計數:" + i);
  }
 }
}, "kira");
t2.setdaemon(true);
t2.start();
thread.sleep(500);
-------------
//輸出:
......
守護線程計數:113755
守護線程計數:113756
守護線程計數:113757
守護線程計數:113758
//結束打印:會發現守護線程并沒有打印500000次,因為主線程已經結束運行了

■ wait 和 notify 機制

wait()使線程停止運行,notify()使停止的線程繼續運行

使用wait()、notify()、notifyall()需要先對調用對象加鎖,即只能在同步方法或同步塊中調用這些方法

調用wait()方法后,線程狀態由running變成waiting,并將當前線程放入對象的等待隊列中

調用notify()或notifyall()方法之后,等待線程不會從wait()返回,需要notify()方法所在同步塊代碼執行完畢而釋放鎖之后,等待線程才可以獲取到該對象鎖并從wait()返回

notify()方法將隨機選擇一個等待線程從等待隊列中移到同步隊列中;notifyall()方法會將等待隊列中的所有等待線線程全部移到同步隊列中,被移動線程狀態由waiting變成blocked

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
// wait/notify 簡單實例
public class numberprint implements runnable {
 private int number;
 public byte[] res;
 public static int count = 5;
 
 public numberprint(int number, byte a[]){
  this.number = number;
  res = a;
 }
 
 @override
 public void run() {
  synchronized (res){
   while (count-- > 0){
    try {
     res.notify(); //喚醒等待res資源的線程,把鎖交給線程(該同步鎖執行完畢自動釋放鎖)
     system.out.println(" " + number);
     res.wait(); //釋放cpu控制權,釋放res的鎖,本線程阻塞,等待被喚醒
     system.out.println("----------線程"+thread.currentthread().getname() + "獲得鎖,wait()后的代碼繼續運行:"+ number);
    } catch (interruptedexception e) {
     e.printstacktrace();
    }
   } //end of while
   return;
  } //syn
 }
 
 public static void main(string[] args) {
  final byte[] a = {0}; //以該對象為共享資源
  new thread(new numberprint(1,a),"1").start();
  new thread(new numberprint(2,a),"2").start();
 }
}

*****各位看客,由于對線程的調度機制還理解比較淺,所以本文會持續更新…… ********

以上這篇淺談多線程_讓程序更高效的運行就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。

原文鏈接:http://www.cnblogs.com/romanjoy/p/7280363.html

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 中文字幕大全 | 日韩一区不卡 | 欧美精品一二区 | 99综合| 亚洲精品久久久久久一区二区 | 国产福利精品一区 | 久久久久久久久久一区二区 | 久久蜜桃av一区二区天堂 | 成人高清免费观看 | 国产专区在线 | 精品久久久久久国产 | 精品一区二区三区蜜桃 | 亚洲天堂网站 | 日韩欧美在线免费观看 | 伊人精品在线 | 亚洲伊人久久综合 | 在线免费观看视频 | 日韩中文字幕视频在线 | 精品96久久久久久中文字幕无 | 亚洲免费电影一区 | 99久久免费精品国产男女性高好 | 在线观看国产视频 | 国产精品99 | 精品国产黄a∨片高清在线 黄色大片aaaa | 日本一区二区在线视频 | 免费一级特黄3大片视频 | 视频一区二区国产 | av黄色在线免费观看 | 91麻豆蜜桃一区二区三区 | 日韩中文字幕视频在线 | a级在线观看 | 91精品国产综合久久久久久 | 中文字幕大全 | 亚洲第一视频 | 一级电影免费在线观看 | 九九视频在线 | 亚洲视频中文字幕 | 久热99| 在线一区二区三区做爰视频网站 | 亚洲国产欧美在线 | 亚洲国产精品激情在线观看 |