zoukankan      html  css  js  c++  java
  • Java之线程处理之二

    No.1编写一个打印机类

    写两个方法

     1 public class Printer {
     2 
     3     public void print1()
     4     {
     5         
     6             System.out.print("微");
     7             System.out.print("冷");
     8             System.out.print("的");
     9             System.out.print("雨");
    10             System.out.println();
    11     }
    12     public void print2()
    13     {
    14         
    15             System.out.print("好");
    16             System.out.print("人");
    17             System.out.println();
    18         
    19         
    20     }
    21 }

    目的:为了使两个线程执行该类中的两个方法

    线程一:

    public class MyThread extends Thread {
        public static Printer p1;
    @Override
    public void run() {
        for (int i = 1; i <=500; i++) {
            p1.print1();
        }
    }

    线程二:

    public class MyThread2 implements Runnable{
        public static Printer p2;
        @Override
        public void run() {
           for (int i = 1; i <=500; i++) {
                p2.print2();
            }
        }
    
    }

    Test类中的方法调用

    public class Test {
    public static void main(String[] args) {
        Printer p=new Printer();
        MyThread t1=new MyThread();
        t1.p1=p;
        t1.start();
        MyThread2 t2=new MyThread2();
        t2.p2=p;
        Thread t3=new Thread(t2);
        t3.start();
        
    }
    }

    则会出现以下情况:因为程序员不能手动干预cpu分配线程资源

    解决方法:加上同步锁,使当一个线程执行完之后另一个线程才有执行的权利 

    public class Printer {
    
        public void print1()
        {
            synchronized (this) {
                System.out.print("微");
                System.out.print("冷");
                System.out.print("的");
                System.out.print("雨");
                System.out.println();
            }
            
        }
        public void print2()
        {
            synchronized (this) {
                System.out.print("好");
                System.out.print("人");
                System.out.println();
            }
            
        }
    }

    解决完毕!!!!!!!!!

  • 相关阅读:
    texarea动态改变监听
    输入配置
    linux 上安装redis 解压之后使用make命令报错
    sql语句能查询出 放在web程序查询不出
    Eclipse 使用git pull 代码时发生冲突的解决办法
    eclipse git 解决冲突
    微信小程序获取openid
    mybatis 一对多 一对一 xml配置
    Eclipse 中撤消git push提交
    idea 开发中遇到的问题
  • 原文地址:https://www.cnblogs.com/chimingyang/p/5769645.html
Copyright © 2011-2022 走看看