Java同期関数コードの詳細
/*
,
*/
// this ,this ,this
// this
// , ,
// obj, this
// , ,
// ,
class Ticket implements Runnable{
private int num = 50;// ,
private Object obj = new Object();
// flag , CPU, flag
// true, , ,
//
boolean flag = true;
public void run(){
if(flag){
while(true){
// , obj, ,
//synchronized(obj){
// this, ,
synchronized(this){// , this Ticket.class,
if(num>0){
// CPU,
try{Thread.sleep(20);}catch(InterruptedException e){e.printStackTrace();}
System.out.println(Thread.currentThread().getName()+"...sale..."+num--);//1
}
}//
}
}
else{
while(true){
fun();
}
}
}
//// , , Class ,
// , , , ,
//public static synchronized void fun(){// Ticket.class
// , ,
public synchronized void fun(){
if(num>0){
// CPU,
try{Thread.sleep(20);}catch(InterruptedException e){e.printStackTrace();}
System.out.println(Thread.currentThread().getName()+"...sale..."+num--);//1
}
}
}
class test{
public static void main(String[] args){
Ticket t = new Ticket();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.start();
//t1 , CPU, CPU
// CPU , flag false,
// , , , ,
// , CPU, t1 CPU,
// t1 , flag true ,
// t1 obj , CPU, flag false
//t2 CPU ,flag false, ,
// this, , , ,
// , , this,
// CPU
try{
Thread.sleep(20);
}catch(InterruptedException e){
e.printStackTrace();
}
t.flag = false;
t2.start();
}
}
締め括りをつける同期関数のロックはthisで、静的同期関数のロックは彼のクラスのバイトコードファイルオブジェクトです。
以上はJava同期関数コードの詳細な内容についてです。皆さんに助けてほしいです。興味のある友達はJavaマルチスレッドFork JoinPoolの実例について詳しく説明します。を参照してください。 Javaはチケットを売ってマルチスレッドを理解する。 Javaスレッド安全基本概念解析など、私達のウェブサイトに対する支持に感謝します。