对代码加锁:
1.在方法前加锁。public synchronized void add(String name) {}
2.在方法里面加锁。synchronized (this) {}
--未加锁
package com.lhj.java;
public class Test extends Thread{
Timer timer=new Timer();
public static void main(String[] args) throws Exception {
Test t = new Test();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
public void run() {
timer.add(Thread.currentThread().getName());//把名字传给add打印
}
}
class Timer{
private static int i=0;
public void add(String name) {
i++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("hello "+name+",i="+i);
}
}
-----------------------------
hello t2,i=2
hello t1,i=2
原因是:t1add的时候将i变成了1,然后t1睡着了,t2add的时候将i变成了2,然后t1醒来打印的i为2,t2醒来打印的i也是2
--在方法前加锁。public synchronized void add(String name) {}
package com.lhj.java;
public class Test extends Thread{
Timer timer=new Timer();
public static void main(String[] args) throws Exception {
Test t = new Test();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
public void run() {
timer.add(Thread.currentThread().getName());//把名字传给add打印
}
}
class Timer{
private static int i=0;
public synchronized void add(String name) {
i++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("hello "+name+",i="+i);
}
}
------------------------
hello t1,i=1
hello t2,i=2
--在方法里面加锁。synchronized (this) {}
package com.lhj.java;
public class Test extends Thread{
Timer timer=new Timer();
public static void main(String[] args) throws Exception {
Test t = new Test();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
t1.setName("t1");
t2.setName("t2");
t1.start();
t2.start();
}
public void run() {
timer.add(Thread.currentThread().getName());//把名字传给add打印
}
}
class Timer{
private static int i=0;
public void add(String name) {
synchronized (this) {
i++;
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("hello "+name+",i="+i);
}
}
}
------------------------
hello t1,i=1
hello t2,i=2
java 多线程锁synchronized
最新推荐文章于 2024-07-11 12:04:35 发布