多线程笔记
1.线程安全概念:
当多个线程访问某一个类(对象或方法)时,这个对象始终都能表现出正确的行为,那么这个类(对象或方法)就是线程安全的。
synchronized:可以在任意对象及方法上加锁,而加锁的这段代码称为"互斥区"或"临界区"
1.1多个线程共用一把锁,多个线程共用多把锁
public class MyThread extends Thread{ private int count = 5 ; //synchronized加锁 没有 public synchronized void run(){ count--; try { Thread.sleep(1000); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } System.out.println(this.currentThread().getName() + " count = "+ count); } // public static void main(String[] args) { // /** // * 共用一把锁 // * 分析:当多个线程访问myThread的run方法时,以排队的方式进行处理(这里排对是按照CPU分配的先后顺序而定的), // * 一个线程想要执行synchronized修饰的方法里的代码: // * 1 尝试获得锁 // * 2 如果拿到锁,执行synchronized代码体内容;拿不到锁,这个线程就会不断的尝试获得这把锁,直到拿到为止, // * 而且是多个线程同时去竞争这把锁。(也就是会有锁竞争的问题) // */ // MyThread myThread = new MyThread(); // Thread t1 = new Thread(myThread,"t1"); // Thread t2 = new Thread(myThread,"t2"); // Thread t3 = new Thread(myThread,"t3"); // Thread t4 = new Thread(myThread,"t4"); // Thread t5 = new Thread(myThread,"t5"); // t1.start(); // t2.start(); // t3.start(); // t4.start(); // t5.start(); // } /* 运行结果 t3:4 t1:3 t2:2 */ public static void main(String[] args) { /** * 每个线程单独一把锁 * 分析:当多个线程访问myThread的run方法时,以排队的方式进行处理(这里排对是按照CPU分配的先后顺序而定的), * 一个线程想要执行synchronized修饰的方法里的代码: * 1 尝试获得锁 * 2 如果拿到锁,执行synchronized代码体内容;拿不到锁,这个线程就会不断的尝试获得这把锁,直到拿到为止, * 而且是多个线程同时去竞争这把锁。(也就是会有锁竞争的问题) */ MyThread myThread1 = new MyThread(); MyThread myThread2 = new MyThread(); MyThread myThread3 = new MyThread(); MyThread myThread4 = new MyThread(); MyThread myThread5 = new MyThread(); Thread t1 = new Thread(myThread1,"t1"); Thread t2 = new Thread(myThread2,"t2"); Thread t3 = new Thread(myThread3,"t3"); Thread t4 = new Thread(myThread4,"t4"); Thread t5 = new Thread(myThread5,"t5"); t1.start(); t2.start(); t3.start(); t4.start(); t5.start(); } }
//多个线程多把锁,没有什么实际作用,一般的是多个线程去更改一个全局变量,所以是多个线程共用一个锁.
1.2类锁
/**
* 关键字synchronized取得的锁都是对象锁,而不是把一段代码(方法)当做锁,
* 所以代码中哪个线程先执行synchronized关键字的方法,哪个线程就持有该方法所属对象的锁(Lock),
*
* 在静态方法上加synchronized关键字,表示锁定.class类,类一级别的锁(独占.class类)。
* @author alienware
*
*/
public class MultiThread {
private int num = 0;
/** static */
public synchronized void printNum(String tag){
try {
if(tag.equals("a")){
num = 100;
System.out.println("tag a, set num over!");
} else {
num = 200;
System.out.println("tag b, set num over!");
}
System.out.println("tag " + tag + ", num = " + num);
} catch (Exception e) {
e.printStackTrace();
}
}
//注意观察run方法输出顺序
public static void main(String[] args) {
//俩个不同的对象
final MultiThread m1 = new MultiThread();
final MultiThread m2 = new MultiThread();
Thread t1 = new Thread(new Runnable() {
public void run() {
m1.printNum("a");
// m2.printNum("a");
}
});
Thread t2 = new Thread(new Runnable() {
public void run() {
m2.printNum("b");
}
});
t1.start();
t2.start();
}
/**
* result:
tag a, set num over!
tag b, set num over!
tag b, num = 200
tag a, num = 100
*/
//锁加在对象上 ,两个线程 互不干扰 ,如果希望打印的内容是 下面的结果 ,可以使用一个对象,或者把 方法静态化 ,即加类锁
/**
* result:
tag a, set num over!
tag a, num = 100
tag b, set num over!
tag b, num = 200
*
*/
1.3对象锁的同步,异步问题
/**
* 对象锁的同步和异步问题
* @author alienware
*
*/
public class MyObject {
public synchronized void method1(){
try {
System.out.println(Thread.currentThread().getName());
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/** synchronized */
public void method2(){
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
final MyObject mo = new MyObject();
/**
* 分析:
* t1线程先持有object对象的Lock锁,t2线程可以以异步的方式调用对象中的非synchronized修饰的方法
* t1线程先持有object对象的Lock锁,t2线程如果在这个时候调用对象中的同步(synchronized)方法则需等待,也就是同步
*/
Thread t1 = new Thread(new Runnable() {
public void run() {
mo.method1();
}
},"t1");
Thread t2 = new Thread(new Runnable() {
public void run() {
mo.method2();
}
},"t2");
t1.start();
t2.start();
}
}
1.4脏读
/** * 业务整体需要使用完整的synchronized,保持业务的原子性。 * @author alienware * */ public class DirtyRead { private String username = "bjsxt"; private String password = "123"; public synchronized void setValue(String username, String password){ this.username = username; try { Thread.sleep(2000); } catch (InterruptedException e) { e.printStackTrace(); } this.password = password; System.out.println("setValue最终结果:username = " + username + " , password = " + password); } public void getValue(){ System.out.println("getValue方法得到:username = " + this.username + " , password = " + this.password); } public static void main(String[] args) throws Exception{ final DirtyRead dr = new DirtyRead(); Thread t1 = new Thread(new Runnable() { public void run() { dr.setValue("z3", "456"); } }); t1.start(); Thread.sleep(1000); dr.getValue(); } } /** result: * getValue方法得到:username = z3 , password = 123 setValue最终结果:username = z3 , password = 456 */ //运行过程 , 当t1线程运行到 setValue()方法之后 ,线程休息2s,主线程休息一秒,运行dr.getValue()方法. 在执行setValue()方法 1.5 synchronizedException /** * synchronized异常 * @author alienware * */ public class SyncException { private int i = 0; public synchronized void operation(){ while(true){ try { i++; Thread.sleep(100); System.out.println(Thread.currentThread().getName() + " , i = " + i); if(i == 20){ //Integer.parseInt("a"); throw new RuntimeException(); } } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) { final SyncException se = new SyncException(); Thread t1 = new Thread(new Runnable() { @Override public void run() { se.operation(); } },"t1"); t1.start(); } }

浙公网安备 33010602011771号