zoukankan      html  css  js  c++  java
  • 多线程

    1继承Thread 

    package cn.mym.basic.util;

    public class Thread1 extends Thread {
    private int count=5;
    private String name;
    public Thread1(String name) {
    this.name=name;
    }
    public void run() {
    for (int i = 0; i < 5; i++) {
    System.out.println(name + "运行 count= " + count--);
    try {
    sleep((int) Math.random() * 10);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }
    public static void main(String[] args) {
    Thread1 mTh1=new Thread1("A");
    Thread1 mTh2=new Thread1("B");
    mTh1.start();
    mTh2.start();
    }
    }

    运行结果:

    2.实现Runnable接口

    package cn.mym.basic.util;

    public class Runnable1 implements Runnable{
    private int count=15;

    public static void main(String[] args) {

    Runnable1 my = new Runnable1();
    new Thread(my, "C").start();//同一个mt,但是在Thread中就不可以,如果用同一个实例化对象mt,就会出现异常
    new Thread(my, "D").start();
    new Thread(my, "E").start();
    }

    public void run() {
    for (int i = 0; i < 6; i++) {
    if(count > 0 ){
    System.out.println(Thread.currentThread().getName() + "运行 count= " + count--);
    }
    try {
    Thread.sleep((int) Math.random() * 10);
    } catch (InterruptedException e) {
    e.printStackTrace();
    }
    }
    }
    }

     运行结果:

    使用第二种方式可以实现资源的共享。

  • 相关阅读:
    利用runtime检測这个对象是否存在某属性?
    Android Studio 使用 SVN 必然遇到问题:commit ** File out of data 问题解决方法
    JPA測试实例
    pat(A) 1063. Set Similarity(STL)
    @Override用在哪儿
    Highcharts数据表示(3)
    #pragma pack (n) 惹的祸
    C++二阶构造函数
    使用自定义的控件
    C++ explicit
  • 原文地址:https://www.cnblogs.com/ouyanxia/p/6410574.html
Copyright © 2011-2022 走看看