zoukankan      html  css  js  c++  java
  • 160407、java实现多线程同步

    多线程就不说了,很好理解,同步就要说一下了。同步,指两个或两个以上随时间变化的量在变化过程中保持一定的相对关系。所以同步的关键是多个线程对象竞争同一个共享资源。
    同步分为外同步和内同步。外同步就是在外部创建共享资源,然后传递到线程中。代码如下:
    1. class MyThread implements java.lang.Runnable {  
    2.     private int threadId;  
    3.     private Object obj;  
    4.   
    5.     public MyThread(int id, Object obj) {  
    6.         this.threadId = id;  
    7.         this.obj = obj;  
    8.     }  
    9.   
    10.     @Override  
    11.     public void run() {  
    12.         synchronized (obj) {//实现obj同步  
    13.             for (int i = 0; i < 100; ++i) {  
    14.                 System.out.println("Thread ID: " + this.threadId + " : " + i);  
    15.             }  
    16.         }  
    17.     }  
    18. }  
    19.   
    20. public class TestThread {  
    21.   
    22.     public static void main(String[] args) throws InterruptedException {  
    23.         Object obj = new Object();  
    24.         for (int i = 0; i < 10; ++i) {  
    25.             new Thread(new MyThread(i, obj)).start();//obj为外部共享资源  
    26.         }  
    27.     }  
    28. }  

        内同步,就是在线程内部创建对象,然后实现同步。因为类成员变量可以被类的所有实例共享,所有可以利用这一特性实现:
    代码如下:
    1. class MyThread implements java.lang.Runnable {  
    2.     private int threadId;  
    3.     private static Object obj = new Object();  
    4.   
    5.     public MyThread(int id) {  
    6.         this.threadId = id;  
    7.     }  
    8.   
    9.     @Override  
    10.     public void run() {  
    11.         synchronized (obj) {  
    12.             for (int i = 0; i < 100; ++i) {  
    13.                 System.out.println("Thread ID: " + this.threadId + " : " + i);  
    14.             }  
    15.         }  
    16.     }  
    17. }  
    18.   
    19. public class TestThread {  
    20.   
    21.     public static void main(String[] args) throws InterruptedException {  
    22.         for (int i = 0; i < 10; ++i) {  
    23.             new Thread(new MyThread(i)).start();  
    24.         }  
    25.     }  
    26. }  
  • 相关阅读:
    C#实现图片的无损压缩
    C#实现图片的无损压缩
    ACM2034
    产品经理入门攻略(三)
    编程思想14.类型信息
    分布式ID生成策略 · fossi
    在加拿大找工作:如何写简历(适用理工科)
    支持向量机 SVM
    javaSE复习之——线程
    spring基于@Value绑定属Bean性失
  • 原文地址:https://www.cnblogs.com/zrbfree/p/5364828.html
Copyright © 2011-2022 走看看