java線程同步
/*
* 線程同步與死鎖
* 1.同步代碼塊
* 2.同步方法
* 線程同步會降低性能的問題,但是提高數據安全性。
*
* 同步準則:
* 1、是代碼塊保持簡短,跟線程變化沒有關係數據移出去處理;
* 2、不要阻塞。如inputstream.read();;
* 3、在持有鎖的時候,不要對其他對象調用方法。
*/
public class MySyncDemo {
public static void main(String[] args){
MyThread mythread=new MyThread();
Thread t1=new Thread(mythread,"TT11");
Thread t2=new Thread(mythread,"TT22");
t1.start();
t2.start();
}
}
class MyThread implements Runnable{
Object obj=new Object();//同步對象
@Override
public void run() {
this.domthod();
/*
* 同步代碼塊
*/
/*synchronized(obj){
System.out.println(Thread.currentThread().getName()+" do something");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" done");
}
*/
}
/*
* 同步方法
*
*/
public synchronized void domthod(){
System.out.println(Thread.currentThread().getName()+" do something");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" done");
}
}
* 線程同步與死鎖
* 1.同步代碼塊
* 2.同步方法
* 線程同步會降低性能的問題,但是提高數據安全性。
*
* 同步準則:
* 1、是代碼塊保持簡短,跟線程變化沒有關係數據移出去處理;
* 2、不要阻塞。如inputstream.read();;
* 3、在持有鎖的時候,不要對其他對象調用方法。
*/
public class MySyncDemo {
public static void main(String[] args){
MyThread mythread=new MyThread();
Thread t1=new Thread(mythread,"TT11");
Thread t2=new Thread(mythread,"TT22");
t1.start();
t2.start();
}
}
class MyThread implements Runnable{
Object obj=new Object();//同步對象
@Override
public void run() {
this.domthod();
/*
* 同步代碼塊
*/
/*synchronized(obj){
System.out.println(Thread.currentThread().getName()+" do something");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" done");
}
*/
}
/*
* 同步方法
*
*/
public synchronized void domthod(){
System.out.println(Thread.currentThread().getName()+" do something");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+" done");
}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.