zoukankan      html  css  js  c++  java
  • Java常用工具——java多线程

    一、线程的创建

    方式一:继承Thread类,重写run()方法

    package com.imooc.thread1;
    
    class MyThread extends Thread{
        public MyThread(String name) {
            super(name);
        }
        public void run() {
            for(int i=1;i<=10;i++) {
                System.out.println(getName()+"正在运行~~"+i);
            }
        }
    }
    public class ThreadTest1 {
        
        public static void main(String[] args) {
            MyThread mt1=new MyThread("线程1");
            MyThread mt2=new MyThread("线程2");
            mt1.start();
            mt2.start();
        }
    }

    2、通过实现Runnable接口创建线程

    package com.imooc.thread3;
    
    class PrintRunnable implements Runnable{
    
        @Override
        public void run() {
            // 重写接口的run()方法
            int i=1;
            while(i<=10) {
                System.out.println(Thread.currentThread().getName()+"正在运行!"+(i++));
            }
            
        }
        
    }
    
    public class Test {
    
        public static void main(String[] args) {
            // 通过实现Runnable接口创建线程
            //1.实例化Runnable接口的实现类
            PrintRunnable pr=new PrintRunnable();
            //2.创建线程对象
            Thread t1=new Thread(pr);
            //3.启动线程
            t1.start();
            PrintRunnable pr2=new PrintRunnable();
            //2.创建线程对象
            Thread t2=new Thread(pr2);
            //3.启动线程
            t2.start();
        }
    
    }

    3、多个线程共享资源

    package com.imooc.thread3;
    
    class PrintRunnable implements Runnable{
        int i=1;
        @Override
        public void run() {
            // 重写接口的run()方法
            
            while(i<=10) {
                System.out.println(Thread.currentThread().getName()+"正在运行!"+(i++));
            }
            
        }
        
    }
    
    public class Test {
    
        public static void main(String[] args) {
            // 通过实现Runnable接口创建线程
            //1.实例化Runnable接口的实现类
            PrintRunnable pr=new PrintRunnable();
            //2.创建线程对象,参数为同一个对象,多个线程共享对象资源
            Thread t1=new Thread(pr);
            Thread t2=new Thread(pr);
            //3.启动线程
            t1.start();
            t2.start();
        }
    
    }
  • 相关阅读:
    系统剪切板的使用UIPasteboard
    iOS开发之GCD总结
    OC报错,after command failed: Directory not empty
    一个女孩被车多次撞到的经历
    iOS一个很好的内存检测工具
    iOS 数据库sqlite3.0操作--超简单--看我就够啦
    推送碰到的一个坑
    iOS之3DTouch的使用---很简单,看我就够啦~~
    简谈造成循环引用的原因以及处理办法
    关于拼过消息推送回调,然后跳转到指定界面
  • 原文地址:https://www.cnblogs.com/loveapple/p/11150034.html
Copyright © 2011-2022 走看看