线程安全
package demo;
/**
* 线程安全测试
* @author 180285
* */
public class MyThread extends Thread{
private int count = 5;
public synchronized void run(){
count--;
System.out.println(this.currentThread().getName()+" count:"+count);
}
/**
* 创建五个线程,线程不安全测试
* @param args
*/
public static void main(String[] args) {
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();
}
结果:
没上锁: 上锁
t2 count:2 t1 count:4
t4 count:1 t4 count:3
t5 count:0 t5 count:2
t1 count:2 t3 count:1
t3 count:2 t2 count:0
多个线程多个对象、类级别的锁
package demo;
public class MutiThread {
private static int num = 0;
public static synchronized void printNum(String tag){
try {
if (tag.equals("a")) {
num = 100;
System.out.println("tag a ,set num over");
Thread.sleep(1000);
} else {
num = 200;
System.out.println("tag b, set num over");
}
System.out.println("tag"+tag+", num: "+num);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
final MutiThread m1 = new MutiThread();
final MutiThread m2 = new MutiThread();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
m1.printNum("a");
}
});
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
m2.printNum("b");
}
});
t1.start();
t2.start();
}
}
结果:
static synchronized时的结果。
tag a ,set num over
taga, num: 100
tag b, set num over
tagb, num: 200
只有synchronized时的结果。
tag a ,set num over
tag b, set num over
tagb, num: 200
taga, num: 100
同步锁、异步锁
- 方法,对象默认都是异步的asynchronized
package demo;
public class MyObject {
public synchronized void method1(){
try {
System.out.println(Thread.currentThread().getName());
Thread.sleep(4000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void method2(){
System.out.println(Thread.currentThread().getName());
}
public static void main(String[] args) {
final MyObject my1 = new MyObject();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
my1.method1();
}
},"t1");
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
my1.method2();
}
},"t2");
t1.start();
t2.start();
}
}
- 上诉结果中,只是打印两个线程的名字,在method2方法没有锁时,t1,t2是同时打印的。上锁之后是先打印t1,4秒之后打印t2。