1.在類中方法上加上
synchronized關鍵字,是對整個對象加鎖,當一個線程通路帶有synchronized的方法時,其他帶有synchronized的方法的通路就都會阻塞。
樣例:
public class threadtest {
public static void main(string[] args) {
stu stu = new stu();
stuthread1 t1 = new stuthread1(stu);
t1.start();
stuthread2 t2 = new stuthread2(stu);
t2.start();
}
class stuthread1 extends thread {
stu stu;
public stuthread1(stu stu) {
this.stu = stu;
public void run() {
stu.read1();
class stuthread2 extends thread {
public stuthread2(stu stu) {
stu.read2();
class stu {
public synchronized void read1() {
system.out.println("read1 begin");
try {
thread.currentthread().sleep(2000);
} catch (interruptedexception e) {
e.printstacktrace();
system.out.println("read1 end");
public synchronized void read2() {
system.out.println("read2 begin");
system.out.println("read2 end");
列印結果為(兩個線程是順序執行的):
read1 begin
read1 end
read2 begin
read2 end
如果去掉read2前面的synchronized關鍵字,列印為(線程出現了交叉執行):
修改read2方法,
public void read2() {
synchronized(this)
{
對this進行加鎖,結果同一次,線程是順序執行的。
最新内容請見作者的github頁:http://qaseven.github.io/