原文:http://blog.csdn.net/yangzhijun_cau/article/details/6432216
线程的同步问题:
1.给要同步的方法前边加上关键字synchronized
2.最好准确到粒度,就要给要同步的代码块加上synchronized块
3.同步问题解决了,但是若要考虑到同步安全问题的话,就要考虑并发性
所以要有锁,其实现为 一、给要同步的方法前面加上锁,String lock = new String("lock");
二、将要同步的代码块变成静态的static
代码如下所附:
1.如下为上边的1:
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);
}
}
}
2.如下为上边的2:
public class ThreadTest1 extends Thread {
private int threadNo;
private String lock;
public ThreadTest1(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 ThreadTest1(i, lock).start();
Thread.sleep(1);
}
}
public void run() {
synchronized (lock) {
for (int i = 1; i < 10000; i++) {
System.out.println("No." + threadNo + ":" + i);
}
}
}
}
3.如下为上边的3:
public class ThreadTest2 extends Thread {
private int threadNo;
public ThreadTest2(int threadNo) {
this.threadNo = threadNo;
}
public static void main(String[] args) throws Exception {
for (int i = 1; i < 20; i++) {
new ThreadTest2(i).start();
Thread.sleep(1);
}
}
public static synchronized void abc(int threadNo) {
for (int i = 1; i < 10000; i++) {
System.out.println("No." + threadNo + ":" + i);
}
}
public void run() {
abc(threadNo);
}
}
注:start()方法为开启线程;run()为线程要执行的方法。