互斥问题描述:
thread1和thread2都调用了output方法,理想的情况下,当thread1调用output方法时,应该一次性打印完“aaaaa”,而当thread2调用output方法,也是一次性打印完“bbbbb”。但在实际的运行中,会出现打印出诸如“aabbbaaa”这种情况,也就是说,thread1正在调用output方法时,thread2插了进来,两个线程同时操作了一个对象中的同一个方法。为了避免这种情况,我们要求,当某个线程在调用output方法时,不允许其他线程调用。
1.
package hc;
public classOutputer {
public void output(String name){
synchronized (this) {
for (int i = 0; i < name.length(); i++) {
System.out.print(name.charAt(i));
}
System.out.println();
}
}
}
2.
package hc;
public classTest2 {
public static void main(String[] args) {
new Test2().init();
}
publicvoidinit(){
final Outputer c = new Outputer();
Threadthread1 = new Thread(new Runnable() {
@Override
public void run() {
while (true) {
try {
Thread.sleep(10);
}catch (InterruptedException e) {
e.printStackTrace();
}
c.output("aaaaa");
}
}
});
thread1.start();
Threadthread2 = new Thread(new Runnable() {
@Override
public void run() {
while(true){
try {
Thread.sleep(10);
}catch (InterruptedException e) {
e.printStackTrace();
}
c.output("bbbbb");
}
}
});
thread2.start();
}
}
同步进程描述:
当两个并发线程访问同一个对象object中的这个synchronized(this)同步代码块时,一个时间内只能有一个线程得到执行。
另一个线程必须等待当前线程执行完这个代码块以后才能执行该代码块。
1.
packagetb;
public class Thread1 implementsRunnable {
public voidrun() {
synchronized(this) {
for (int i = 0; i < 5; i++) { //循环执行5次
System.out.println(Thread.currentThread().getName()+" synchronized loop " + i);
}
}
}
}
2.
package tb;
import tb.Thread1;
public classMain {
public static void main(String[] args) {
Thread1t1 = newThread1();
Threadta = new Thread(t1, "A");
Threadtb = new Thread(t1, "B");
ta.start();
tb.start();
}
}