狼王给你发文章连接了,理论也就不用说了。
写段代码测试下不就知道了!
- package cn.itcast;
- public class ThreadTest {
- private int i = 0;
- public static void main(String agrs[]) {
- ThreadTest tt = new ThreadTest();
- inc in = tt.new inc();
- dec de = tt.new dec();
- for(int j=0;j<2;j++){
- Thread t=new Thread(in);
- t.start();
- t=new Thread(de);
- t.start();
- }
- }
- private synchronized void inc() {
- i ++;
- System.out.println(Thread.currentThread().getName()+"+inc:"+i);
- }
- private synchronized void dec() {
- i --;
- System.out.println(Thread.currentThread().getName()+"-inc:"+i);
- }
- class inc implements Runnable {
- public void run() {
- for(int j=0;j<100;j++)
- {
- inc();
- }
- }
- }
- class dec implements Runnable {
- public void run() {
- for(int j=0;j<100;j++)
- {
- dec();
- }
- }
- }
- }
复制代码
你把synchronized去掉,看看和加上的区别 |