时间:2019-12-14 17:17:23
实现Runnable接口的方式这样写:
回顾下Runnable实的多线程是共享同一对象的,所以synchronized 的共享对象就是this
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
|
package cn.tx.demo4;
public class SaleTicked implements Runnable {
int tickets = 100;
private String name;
private Object obj = new Object();
@Override
public void run() {
while (true){
if(saleTick()){
break;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//此时共享对就是this
public synchronized boolean saleTick(){
boolean isflag = false;
if(tickets > 0){
System.out.println(Thread.currentThread().getName() + "卖出的座位是"+(tickets--));
}else{
isflag = true;
}
return isflag;
}
}
|
继承Thread的方式:
回顾实现方式为继承Thread的run方法,实现多线程时NEW了多个Thread对象,且共享数据是以类属性实现的此时代码为:
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
|
package cn.tx.demo2;
public class SaleTickedThread extends Thread {
private String name;
/**
* 定义共享的数据
*/
static int tickets = 100;
//创建一个锁对象(用静态实现共享)
static Object obj = new Object();
public SaleTickedThread(String name) {
this.name = name;
}
@Override
public void run() {
//卖票是一个持续的动作
while (true){
if(saleTick()){
break;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(name + "卖票结束");
}
//这里调整为类方法了
public static synchronized boolean saleTick(){
boolean isflag = false;
if(tickets > 0){
System.out.println(Thread.currentThread().getName() + "卖出的座位是"+(tickets--));
}else{
isflag = true;
}
return isflag;
}
}
|
如果不调整为类方法就是4个锁对象,线程会现在不安全问题
