學習JAVA第二十天
阿新 • • 發佈:2021-08-23
多執行緒同步
class SyncCounter1{
public static void main(String[] args){
Num num = new Num();
Thread counter1 = new Counter(num);
Thread counter2 = new Counter(num);
for( int i=0; i<10; i++ ){
if(!num.testEquals()) break;
try{
Thread.sleep(100);
}catch(InterruptedException e){
}
}
}
} class Num
{
private int x=0;
private int y=0;
void increase(){
x++;
y++;
}
boolean testEquals(){
boolean ok = (x==y);
System.out.println( x + "," + y +" :" + ok);
return ok;
}
} class Counter extends Thread
{
private Num num;
Counter( Num num ){
this.num = num;
this.setDaemon(true);
this.setPriority(MIN_PRIORITY);
this.start();
}
public void run(){
while(true){
num.increase();
}
}
} 2.同步 java有互斥鎖,保證共享資料操作的完整性 關鍵字 synchronized 用來與物件的互斥鎖聯絡 *synchronized用法 synchronized(物件){ ... } synchronized(this) class SyncCounter2
{
public static void main(String[] args){
Num num = new Num();
Thread counter1 = new Counter(num);
Thread counter2 = new Counter(num);
for( int i=0; i<10; i++ ){
num.testEquals();
try{
Thread.sleep(100);
}catch(InterruptedException e){
}
}
}
} class Num
{
private int x=0;
private int y=0;
synchronized void increase(){
x++;
y++;
}
synchronized boolean testEquals(){
boolean ok = (x==y);
System.out.println( x + "," + y +" :" + ok);
return ok;
}
} class Counter extends Thread
{
private Num num;
Counter( Num num ){
this.num = num;
this.setDaemon(true);
this.setPriority(MIN_PRIORITY);
this.start();
}
public void run(){
while(true){
num.increase();
}
}
} 3.執行緒的死鎖 class Worker
{
int id;
public Worker(int id){ this.id=id; }
synchronized void doTaskWithCooperator(Worker other){
try{ Thread.sleep(500); } catch(Exception e){}
synchronized(other){
System.out.println("doing" + id);
}
}
} class DeadLockDemo{
public static void main(String[] args) {
Worker w1 = new Worker(1);
Worker w2 = new Worker(2);
Thread td1 = new Thread(()->{
w1.doTaskWithCooperator(w2);
});
Thread td2 = new Thread(()->{
w2.doTaskWithCooperator(w1);
});
td1.start();
td2.start();
}
}