在java中synchronized是多个线程共享同一段代码的锁。
多线程并发方法有:
1 加锁
2 信号量
3 阻塞---唤醒
当有多个线程并发执行同一块代码块时,加锁可以让一段时间内只有一个线程在执行,保证了业务的原子操作。
例如下面:
package andy.thread.traditional.test;
/**
* @author Zhang,Tianyou
* @version 2014年11月8日 下午11:02:53
*/
// 使用synchronized加同步锁
public class ThreadSynchronizedTest {
public static void main(String[] args) {
A a = new A();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
a.printfA(Thread.currentThread().getName()
+ "hello, my is A");
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
a.printfA(Thread.currentThread().getName()
+ "hello, my is B");
}
}
}).start();
}
static class A {
public void printfA(String name) {
for (int i = 0; i < name.length(); i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}
}
}
Thread-1hello, my is B
Thread-1hello, my is B
Thread-0hello, my is A
ThThread-0hello, my is A
read-1hello, my is B
Thread-1helTlhreoad-0hello, my is A
, my is B
Thread-0hello, my is A
Thread-1hello, my is B
Thread-0hello, my is A
这是为了防止多线程并发执行时,确保只有一个在使用我们可以加同步锁。
synchronized(name){
// 加锁的代码块, name为锁标志
}
syschronized 可以加在方法里和方法内:
package andy.thread.traditional.test;
/**
* @author Zhang,Tianyou
* @version 2014年11月8日 下午11:02:53
*/
// 使用synchronized加同步锁
public class ThreadSynchronizedTest {
public static void main(String[] args) {
A a = new A();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
a.printfA(Thread.currentThread().getName()
+ "hello, my is A");
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
a.printfA(Thread.currentThread().getName()
+ "hello, my is B");
}
}
}).start();
}
static class A {
public void printfA(String name) {
synchronized (A.class) {
for (int i = 0; i < name.length(); i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}
}
public synchronized void printfB(String name) {
for (int i = 0; i < name.length(); i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}
}
}
运行效果如下:
Thread-1hello, my is B
Thread-0hello, my is A
Thread-1hello, my is B
Thread-0hello, my is A
Thread-1hello, my is B
Thread-0hello, my is A
Thread-1hello, my is B
Thread-0hello, my is A
Thread-1hello, my is B
Thread-0hello, my is A
Thread-1hello, my is B
Thread-0hello, my is A
Thread-1hello, my is B
Thread-0hello, my is A
Thread-1hello, my is B