线程问题
线程锁为threadNo,每个线程threadNo唯一,达不到互斥最后资源recources不能同步
package len_server;
public class ThreadTest2 extends Thread {
private String threadNo;
private String lock;
private static int recources=100;//需要同步的资源对象
public ThreadTest2(String threadNo,String lock) {
this.threadNo = threadNo;
this.lock=lock;
}
public static void main(String[] args) throws InterruptedException {
for (int i = 1; i <=3; i++) {
ThreadTest2 t=new ThreadTest2(String.valueOf(i),"abc");
t.start();
}
sleep(2000);
System.out.println("=================================");
System.out.println(recources);//打印结果
}
public void run() {
synchronized (this.getThreadNo()) {
int flag=recources; //模拟查询余额
try {
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
recources=flag+1;//模拟存款
}
}
public String getThreadNo() {
return threadNo;
}
public void setThreadNo(String threadNo) {
this.threadNo = threadNo;
}
public String getLock() {
return lock;
}
public void setLock(String lock) {
this.lock = lock;
}
}
线程锁为lock,每个线程的lock相同,也就是锁对象相同能实现资源同步
package len_server;
public class ThreadTest2 extends Thread {
private String threadNo;
private String lock;
private static int recources=100;//需要同步的资源对象
public ThreadTest2(String threadNo,String lock) {
this.threadNo = threadNo;
this.lock=lock;
}
public static void main(String[] args) throws InterruptedException {
for (int i = 1; i <=3; i++) {
ThreadTest2 t=new ThreadTest2(String.valueOf(i),"abc");
t.start();
}
sleep(2000);
System.out.println("=================================");
System.out.println(recources);//打印结果
}
public void run() {
synchronized (this.getLock()) {
int flag=recources; //模拟查询余额
try {
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
recources=flag+1;//模拟存款
}
}
public String getThreadNo() {
return threadNo;
}
public void setThreadNo(String threadNo) {
this.threadNo = threadNo;
}
public String getLock() {
return lock;
}
public void setLock(String lock) {
this.lock = lock;
}
}
猜猜分别输出结果?