博客出自:http://blog.csdn.net/liuxian13183,转载注明出处!
All Rights Reserved !
关于锁,需要在特殊时刻用到,今天就来小分析一把。
public class ThreadTest extends Thread {
private int threadNo;
public ThreadTest(int threadNo) {
this.threadNo = threadNo;
}
public static void main(String[] args) throws Exception {
for (int i = 1; i < 10; i++) {
new ThreadTest(i).start();
Thread.sleep(1);
}
}
@Override
public synchronized void run() {
for (int i = 1; i < 10000; i++) {
System.out.println("No." + threadNo + ":" + i);
}
}
}
这个程序实际上是以ThreadTest对象做为锁,将run方法执行的,实际上是对每个线程都没有加锁,就像一个门有一把锁,但十个都有钥匙,所以线程执行非常乱。
view plaincopy to clipboardprint?
public class ThreadTest2 extends Thread {
private int threadNo; private String lock;
public ThreadTest2(int threadNo, String lock) {
this.threadNo = threadNo;
this.lock = lock; }
public static void main(String[] args) throws Exception {
String lock = new String("lock");
for (int i = 1; i < 10; i++) {
new ThreadTest2(i, lock).start();
Thread.sleep(1);
}
}
public void run() {
synchronized (lock) {
for (int i = 1; i < 10000; i++) {
System.out.println("No." + threadNo + ":" + i);
}
}
}
}
这个程序是对每个run方法,加一个特定的锁lock,但这个对象是所以线程共用的,就像十个人共用一个厕所的门,只能一个一个来。
关于锁的用途在于,如果拍摄一张照片,只有保存成功才能进行传输;所用保存时,先锁住;保存完毕,锁自然解开,就可以传输查看了。
尼玛呀,吐个槽,CSDN怎么搞的,我把代码贴上,总是给我居中显示,把所有格式都去掉都不行,不知道怎么搞的。