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();
        }
    
    }
  • 相关阅读:
    jvm 优化
    SqlServer体系结构
    sqlserver2012 在视图中建索引
    win10 桌面设置为远程桌面
    ORACLE 查询某表中的某个字段的类型,是否为空,是否有默认值等
    activemq读取剩余消息队列中消息的数量
    Oracl 一条sql语句 批量添加、修改数据
    ClickOnce一项Winform部署
    C#语言中的修饰符
    关于MySQL集群的一些看法
  • 原文地址:https://www.cnblogs.com/loveapple/p/11150034.html
Copyright © 2011-2022 走看看