多个线程访问synchronized和非synchronized代码块

class Counter implements Runnable{
private int count;

public Counter() {
count = 0;
}

public void countAdd() {
synchronized(this) {
for (int i = 0; i < 5; i ++) {
try {
System.out.println(Thread.currentThread().getName() + “:” + (count++));
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}

//非synchronized代码块,未对count进行读写操作,所以可以不用synchronized
public void printCount() {
for (int i = 0; i < 5; i ++) {
try {
System.out.println(Thread.currentThread().getName() + " count:" + count);
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}

public void run() {
String threadName = Thread.currentThread().getName();
if (threadName.equals(“A”)) {
countAdd();
} else if (threadName.equals(“B”)) {
printCount();
}
}
}
调用代码:
Counter counter = new Counter();
Thread thread1 = new Thread(counter, “A”);
Thread thread2 = new Thread(counter, “B”);
thread1.start();
thread2.start();
运行结果:
A:0
B count:1
A:1
B count:2
A:2
B count:3
A:3
B count:4
A:4
B count:5

猜你喜欢

转载自blog.csdn.net/weixin_42866896/article/details/82957667
今日推荐