zoukankan      html  css  js  c++  java
  • 关于线程间的通信的几个解决事例

    public class MySynchronizedTest implements Runnable {//线程加锁时应是同一对象
    int i=100;
    Object object=new Object();
    boolean flag=true;
    //对方法加锁
    public synchronized void count1()
    {
    while(flag){
    try {//睡眠200ms
    Thread.sleep(200);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    if(this.i>0)
    {
    System.out.println(Thread.currentThread().getName()+"在执行。。。");
    i--;
    System.out.println("i="+i);
    }
    else{
    flag=false;
    }
    }

    }
    public void run() {
    //count1();
    while(flag){
    try {//睡眠200ms
    Thread.sleep(1/2);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    synchronized (object) {
    if(this.i>0)
    {System.out.println(Thread.currentThread().getName()+"在执行。。。");
    i--;
    System.out.println("i="+i);
    }

    }


    }

    }
    }

    上述做了个简单的加锁方式的事例

    public void print(int i)
    {synchronized (this) {//如果为this和print3同步,如果为this.getClass就和3同步
    System.out.println(Thread.currentThread().getName()+"正在执行。。");
    System.out.println(i);
    }

    }
    //和该对象的全局变量互斥,比如this。getclass
    public static synchronized void print2(int i)
    {
    System.out.println(Thread.currentThread().getName()+"正在执行。。");
    System.out.println(i);
    }
    public synchronized void print3(int i)
    {
    System.out.println(Thread.currentThread().getName()+"正在执行。。");
    System.out.println(i);
    }

    }

    方法模块间的线程同步

    public class MyMainThreadCommunication {

    /**
    * @param args
    */
    public static void main(String[] args) {
    Thread thread=new Thread(new MyThrad());
    /*for(int i=0;i<10;i++)
    {
    thread.start();

    }
    */
    for(int j=0;j<10;j++){
    new Thread(new MyThrad()).start();
    synchronized (MyMainThreadCommunication.class) {


    for(int i=0;i<10;i++)
    {
    System.out.println(i+"主线程正在执行。。。。。。。");

    }
    }
    }

    }

    }

    public class MyThrad implements Runnable{

    public void run() {
    //和MyMainThreadCommunication.class的main中的主线程互斥
    synchronized(MyMainThreadCommunication.class) {
    for(int i=0;i<15;i++)
    {
    System.out.println(i+"子线程正在执行。。");
    try {
    Thread.sleep(2000);
    } catch (InterruptedException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
    }
    System.out.println("唤醒");
    }

    }

    }

    }

    上述关于非同一个对象的所产生的线程实现同步

    关于守护线程,守护线程是一个服务型线程,在没有其它线程时,守护线程自动退出!!!!!!

  • 相关阅读:
    pycharm-1
    WIN7、WIN10 右键在目录当前打开命令行Cmd窗口
    富文本框TinyMCE上传本地图片基本配置
    安装win10正式版后网速变慢的解决方法
    win10远程桌面出现身份验证错误。要求的函数不受支持
    C# 利用VS自带的WSDL工具生成WebService服务类
    解决IIS服务使用C#代码在Windows Server 2012上无法启动Excel的问题
    chorme浏览器不支持audio/video中的autoplay属性的解决方法
    iOS 内购笔记
    利用SortedMap对HashMap进行排序
  • 原文地址:https://www.cnblogs.com/mengziHEHE/p/3222001.html
Copyright © 2011-2022 走看看