java多线程中,锁不起作用?
package com.multi;
public class ThreadTest implements Runnable {
private Integer ticket = 10;
private Integer count = 0;
private byte[] lock = new byte[0];
public void run() {
synchronized (ticket) {
while (true) {
if (ticket <= -100) {
break;
}
System.out.println(String.format("thread: %s , tiketnum = %d do some thing"
,Thread.currentThread().getName()
,ticket--));
count++;
}
}
}
public static void main(String[] args) {
ThreadTest mTh1 = new ThreadTest();
Thread[] th = new Thread[5];
for (int i = 0; i < 5; i++) {
th[i]= new Thread(mTh1,"th"+i);
th[i].start();
}
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(mTh1.count);
}
}
执行结果
thread: th4 , tiketnum = 6 do some thing
thread: th3 , tiketnum = 7 do some thing
thread: th4 , tiketnum = 5 do some thing
thread: th3 , tiketnum = 4 do some thing
thread: th3 , tiketnum = 2 do some thing
thread: th4 , tiketnum = 3 do some thing
thread: th4 , tiketnum = 0 do some thing
thread: th4 , tiketnum = -1 do some thing
thread: th4 , tiketnum = -2 do some thing
thread: th4 , tiketnum = -3 do some thing
thread: th4 , tiketnum = -4 do some thing
thread: th4 , tiketnum = -5 do some thing
thread: th4 , tiketnum = -6 do some thing
thread: th4 , tiketnum = -7 do some thing
thread: th4 , tiketnum = -8 do some thing
thread: th1 , tiketnum = 9 do some thing
……………………
…………