线程有四种状态:
1) 创建(new)
2) 就绪(Runnable)
3) 阻塞(Blocked)
4) 结束(Dead)
线程在以下情况下,会进入阻塞状态:
1) 调用sleep()
2) 调用wait()
3) I/O阻塞;因获取其他对象的对象锁而阻塞。
wait 和 notify的使用:
wait 和 notify的使用
1) 这两个方法都必须是在synchronized代码块或方法中使用。
2) wait一般是自己调用。而别人再进行notify()
调用sleep()的时候,锁并没有释放;而wait()方法的确释放了锁。这意味着在调用wait()期间,可以调用线程中对象的其他同步控制方法。
在多线程并发的情况下,使用yield()这个让步方法。可以让并发更加均衡。
sleep(),wait(),join()方法都必须进行try...catch,因为都有可能受interrupt所影响。
synchronized注意的地方:
synchronized代码块是对指定的对象进行加锁;synchronized方法是对本身对象进行加锁,等同于synchronized(this){}。
所以两者从机制上,没有大的区别。
注意,互斥只有在竞争者之间才会互斥;即只有争夺共享锁的之间才会互斥。
例如以下代码中,在调用sync1()的时候,同时再调用sync2(),则会互斥。而同时调用notSync()则不会互斥。
package bison.sample;
public class SynchronizedDemo {
public synchronized void sync1() {
try {
System.out.println("sync1 start sleep...");
Thread.sleep(10 * 1000);
System.out.println("sync1 end sleep");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void sync2() {
try {
System.out.println("sync2 start sleep...");
Thread.sleep(10 * 1000);
System.out.println("sync2 end sleep");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void notSync(){
System.out.println("notSync hello");
}
}
分享到:
相关推荐
这是为VC++进阶爱好者学习的源代码,全都通过编译
在这里聚集了有关进程和多线程的实例,基本上能遇到的问题在里面都能体现出来
foreach (ProcessThread t in ps) { AllCurrentThreadIDs.Add(t.Id, null); } int[] IDs = (int[])TaskThreadIDs.Clone(); foreach (int ID in IDs) { if (!AllCurrentThreadIDs.ContainsKey(ID)) ...
foreach (ProcessThread t in ps) { AllCurrentThreadIDs.Add(t.Id, null); } int[] IDs = (int[])TaskThreadIDs.Clone(); foreach (int ID in IDs) { if (!AllCurrentThreadIDs.ContainsKey(ID)) ...
Process Monitor is an advanced monitoring tool for Windows that shows real-time file system, Registry and process/thread activity. It combines the features of two legacy Sysinternals utilities, ...
sample source for process and thread. it compiled in evc++4
Process Monitor is an advanced monitoring tool for Windows that shows real-time file system, Registry and process/thread activity. It combines the features of two legacy Sysinternals utilities, ...
│ │ ProcessThread.cpp │ │ ProcessThread.h │ │ ReadMe.txt │ │ resource.h │ │ Services.cpp │ │ Services.h │ │ ShadowSSDT.cpp │ │ ShadowSSDT.h │ │ SSDT.cpp │ │ SSDT.h │ │ stdafx.cpp...
Process Monitor is an advanced monitoring tool for Windows that shows real-time file system, Registry and process/thread activity. It combines the features of two legacy Sysinternals utilities, ...
操作系统课件:02_process_thread.ppt
UTL_logDebug( "Process thread started" ); thrControlInit(); thrControlStartup(); UTL_logDebug( "Control thread started" ); /* create all SCOM and message objects */ SCOM_create("INTOPROC", ...
操作系统英文课件:ch2a Process and Thread.ppt
操作系统英文课件:ch2b Process and Thread.ppt
操作系统英文课件:ch2c Process and Thread.ppt
前端大厂最新面试题-thread_process.docx
JAVA语言实现对图像进程的控制和操作,内含25个文件