62,614
社区成员
发帖
与我相关
我的任务
分享
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
*
* @author qi
*/
public class SyncLockDemo2 {
public static void main(String[] xxx) {
Thread[] threads = new Thread[100];
final long t = System.nanoTime();
Runtime.getRuntime().addShutdownHook(new Thread(){
@Override
public void run(){
System.err.println((System.nanoTime()-t)/1000000);
}
});
final byte[] lock1 = new byte[0];
final Lock lock2 = new ReentrantLock();
for (int i = 0; i < threads.length; i++) {
final int index = i;
Runnable run = new Runnable() {
public void run() {
synchronized (lock1) {
for (int k = 0; k < 1000; k++) {
System.out.println(index + ":" + k);
}
}
}
};
threads[i] = new Thread(run);
}
// for (int i = 0;
// i < threads.length;
// i++) {
// final int index = i;
// Runnable run = new Runnable() {
//
// public void run() {
// try {
// lock2.lock();
// for (int k = 0; k < 1000; k++) {
// System.out.println(index + ":" + k);
// }
// } finally {
// lock2.unlock();
// }
// }
// };
// threads[i] = new Thread(run);
//// threads[i].setDaemon(true);
// }
for (int i = 0;
i < threads.length;
i++) {
threads[i].start();
}
}
}