服务器之家:专注于VPS、云服务器配置技术及软件下载分享
分类导航

PHP教程|ASP.NET教程|Java教程|ASP教程|编程技术|正则表达式|C/C++|IOS|C#|Swift|Android|VB|R语言|JavaScript|易语言|vb.net|

服务器之家 - 编程语言 - Java教程 - java多线程之线程,进程和Synchronized概念初解

java多线程之线程,进程和Synchronized概念初解

2021-02-22 11:43徐刘根 Java教程

这篇文章主要介绍了java多线程之线程,进程和Synchronized概念初解,涉及进程与线程的简单概念,实现多线程的方式,线程安全问题,synchronized修饰符等相关内容,具有一定借鉴价值,需要的朋友可以参考下。

一、进程线程的概念

(1)在传统的操作系统中,程序并不能独立运行,作为资源分配和独立运行的基本单位都是进程。

在未配置 os 的系统中,程序的执行方式是顺序执行,即必须在一个程序执行完后,才允许另一个程序执行;在多道程序环境下,则允许多个程序并发执行。程序的这两种执行方式间有着显著的不同。也正是程序并发执行时的这种特征,才导致了在操作系统中引入进程的概念。

自从在 20 世纪 60 年代人们提出了进程的概念后,在 os 中一直都是以进程作为能拥有资源和独立运行的基本单位的。直到 20 世纪 80 年代中期,人们又提出了比进程更小的能独立运行的基本单位——线程(threads),试图用它来提高系统内程序并发执行的程度,从而可进一步提高系统的吞吐量。特别是在进入 20 世纪 90 年代后,多处理机系统得到迅速发展,线程能比进程更好地提高程序的并行执行程度,充分地发挥多处理机的优越性,因而在近几年所推出的多处理机 os 中也都引入了线程,以改善 os 的性能。

—–以上摘自《计算机操作系统-汤小丹等编著-3 版》

(2)下图是来自知乎用户的解释:

java多线程之线程,进程和Synchronized概念初解

通过上述的大致了解,基本知道线程和进程是干什么的了,那么我们下边给进程和线程总结一下概念:

(3)进程(process)是计算机中的程序关于某数据集合上的一次运行活动,是系统进行资源分配和调度的基本单位,是操作系统结构的基础。在早期面向进程设计的计算机结构中,进程是程序的基本执行实体;在当代面向线程设计的计算机结构中,进程是线程的容器。程序是指令、数据及其组织形式的描述,进程是程序的实体。

(4)线程,有时被称为轻量级进程(lightweight process,lwp),是程序执行流的最小单元。线程是程序中一个单一的顺序控制流程。进程内一个相对独立的、可调度的执行单元,是系统独立调度和分派cpu的基本单位指运行中的程序的调度单位。在单个程序中同时运行多个线程完成不同的工作,称为多线程

(5)进程和线程的关系:

java多线程之线程,进程和Synchronized概念初解

二、java实现多线程方式

(1)继承thread,重写run()方法

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class mythread extends thread {
 
  @override
  public void run() {
    while (true) {
      system.out.println(this.currentthread().getname());
    }
  }
 
  public static void main(string[] args) {
    mythread thread = new mythread();
    thread.start(); //线程启动的正确方式
  }
}

输出结果:

?
1
2
3
4
thread-0
thread-0
thread-0
...

另外,要明白启动线程的是start()方法而不是run()方法,如果用run()方法,那么他就是一个普通的方法执行了。

(2)实现runable接口

?
1
2
3
4
5
6
7
8
9
10
11
12
13
public class myrunnable implements runnable {
 
  @override
  public void run() {
    system.out.println("123");
  }
 
  public static void main(string[] args) {
    myrunnable myrunnable = new myrunnable();
    thread thread = new thread(myrunnable, "t1");
    thread.start();
  }
}

三、线程安全

线程安全概念:当多个线程访问某一个类(对象或方法)时,这个类始终能表现出正确的行为,那么这个类(对象或方法)就是线程安全的。

线程安全就是多线程访问时,采用了加锁机制,当一个线程访问该类的某个数据时,进行保护,其他线程不能进行访问直到该线程读取完,其他线程才可使用。不会出现数据不一致或者数据污染。 线程不安全就是不提供数据访问保护,有可能出现多个线程先后更改数据造成所得到的数据是脏数据。这里的加锁机制常见的如:synchronized

四、synchronized修饰符

(1)synchronized:可以在任意对象及方法上加锁,而加锁的这段代码称为“互斥区”或“临界区”。

(2)**不使用**synchronized实例(代码a):

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
public class mythread extends thread {
    private int count = 5;
    @override
      public void run() {
        count--;
        system.out.println(this.currentthread().getname() + " count:" + count);
    }
    public static void main(string[] args) {
        mythread mythread = new mythread();
        thread thread1 = new thread(mythread, "thread1");
        thread thread2 = new thread(mythread, "thread2");
        thread thread3 = new thread(mythread, "thread3");
        thread thread4 = new thread(mythread, "thread4");
        thread thread5 = new thread(mythread, "thread5");
        thread1.start();
        thread2.start();
        thread3.start();
        thread4.start();
        thread5.start();
    }
}

输出的一种结果如下:

?
1
2
3
4
5
thread3 count:2
thread4 count:1
thread1 count:2
thread2 count:3
thread5 count:0

可以看到,上述的结果是不正确的,这是因为,多个线程同时操作run()方法,对count进行修改,进而造成错误。

(3)**使用**synchronized实例(代码b):

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public class mythread extends thread {
 
  private int count = 5;
 
  @override
  public synchronized void run() {
    count--;
    system.out.println(this.currentthread().getname() + " count:" + count);
  }
 
  public static void main(string[] args) {
    mythread mythread = new mythread();
    thread thread1 = new thread(mythread, "thread1");
    thread thread2 = new thread(mythread, "thread2");
    thread thread3 = new thread(mythread, "thread3");
    thread thread4 = new thread(mythread, "thread4");
    thread thread5 = new thread(mythread, "thread5");
    thread1.start();
    thread2.start();
    thread3.start();
    thread4.start();
    thread5.start();
  }
}

输出结果:

?
1
2
3
4
5
thread1 count:4
thread2 count:3
thread3 count:2
thread5 count:1
thread4 count:0

可以看出代码a和代码b的区别就是在run()方法上加上了synchronized修饰。

说明如下:

当多个线程访问mythread 的run方法的时候,如果使用了synchronized修饰,那个多线程就会以排队的方式进行处理(这里排队是按照cpu分配的先后顺序而定的),一个线程想要执行synchronized修饰的方法里的代码,首先是尝试获得锁,如果拿到锁,执行synchronized代码体的内容,如果拿不到锁的话,这个线程就会不断的尝试获得这把锁,直到拿到为止,而且多个线程同时去竞争这把锁,也就是会出现锁竞争的问题。

五、一个对象有一把锁!多个线程多个锁!

何为,一个对象一把锁,多个线程多个锁!首先看一下下边的实例代码(代码c):

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class multithread {
 
  private int num = 200;
 
  public synchronized void printnum(string threadname, string tag) {
    if (tag.equals("a")) {
      num = num - 100;
      system.out.println(threadname + " tag a,set num over!");
    } else {
      num = num - 200;
      system.out.println(threadname + " tag b,set num over!");
    }
    system.out.println(threadname + " tag " + tag + ", num = " + num);
  }
 
  public static void main(string[] args) throws interruptedexception {
    final multithread multithread1 = new multithread();
    final multithread multithread2 = new multithread();
 
    new thread(new runnable() {
      public void run() {
        multithread1.printnum("thread1", "a");
      }
    }).start();
 
    thread.sleep(5000);
    system.out.println("等待5秒,确保thread1已经执行完毕!");
 
    new thread(new runnable() {
      public void run() {
        multithread2.printnum("thread2", "b");
      }
    }).start();
  }
}

输出结果:

?
1
2
3
4
5
thread1 tag a,set num over!
thread1 tag a, num = 100
等待5秒,确保thread1已经执行完毕!
thread2 tag b,set num over!
thread2 tag b, num = 0

可以看出,有两个对象:multithread1和multithread2,如果多个对象使用同一把锁的话,那么上述执行的结果就应该是:thread2 tag b, num = -100,因此,是每一个对象拥有该对象的锁的。

关键字synchronized取得的锁都是对象锁,而不是把一段代码或方法当做锁,所以上述实例代码c中哪个线程先执行synchronized 关键字的方法,那个线程就持有该方法所属对象的锁,两个对象,线程获得的就是两个不同对象的不同的锁,他们互补影响的。

那么,我们在正常的场景的时候,肯定是有一种情况的就是,所有的对象会对一个变量count进行操作,那么如何实现哪?很简单就是加static,我们知道,用static修改的方法或者变量,在该类的所有对象是具有相同的引用的,这样的话,无论实例化多少对象,调用的都是一个方法,代码如下(代码d):

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
public class multithread {
 
  private static int num = 200;
 
  public static synchronized void printnum(string threadname, string tag) {
    if (tag.equals("a")) {
      num = num - 100;
      system.out.println(threadname + " tag a,set num over!");
    } else {
      num = num - 200;
      system.out.println(threadname + " tag b,set num over!");
    }
    system.out.println(threadname + " tag " + tag + ", num = " + num);
  }
 
  public static void main(string[] args) throws interruptedexception {
    final multithread multithread1 = new multithread();
    final multithread multithread2 = new multithread();
 
    new thread(new runnable() {
      public void run() {
        multithread1.printnum("thread1", "a");
      }
    }).start();
 
    thread.sleep(5000);
    system.out.println("等待5秒,确保thread1已经执行完毕!");
 
    new thread(new runnable() {
      public void run() {
        multithread2.printnum("thread2", "b");
      }
    }).start();
  }
}

输出结果:

?
1
2
3
4
5
thread1 tag a,set num over!
thread1 tag a, num = 100
等待5秒,确保thread1已经执行完毕!
thread2 tag b,set num over!
thread2 tag b, num = -100

可以看出,对变量和方法都加上了static修饰,就可以实现我们所需要的场景,同时也说明了,对于非静态static修饰的方法或变量,是一个对象一把锁的。

六、对象锁的同步和异步

(1)同步:synchronized

同步的概念就是共享,我们要知道“共享”这两个字,如果不是共享的资源,就没有必要进行同步,也就是没有必要进行加锁;

同步的目的就是为了线程的安全,其实对于线程的安全,需要满足两个最基本的特性:原子性和可见性;

(2)异步:asynchronized

异步的概念就是独立,相互之间不受到任何制约,两者之间没有任何关系。

(3)示例代码:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
public class myobject {
 
  public void method() {
    system.out.println(thread.currentthread().getname());
  }
 
  public static void main(string[] args) {
    final myobject myobject = new myobject();
 
    thread t1 = new thread(new runnable() {
      public void run() {
        myobject.method();
      }
    }, "t1");
 
    thread t2 = new thread(new runnable() {
      public void run() {
        myobject.method();
      }
    }, "t2");
 
    t1.start();
    t2.start();
  }
}

上述代码中method()就是异步的方法。

总结

以上就是本文关于java多线程之线程,进程和synchronized概念初解的全部内容,希望对大家有所帮助。如有不足之处,欢迎留言指出,小编会及时回复大家的。

原文链接:http://blog.csdn.net/xlgen157387/article/details/77920497

延伸 · 阅读

精彩推荐