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();
        }
    
    }
  • 相关阅读:
    C# Tips Written By Andrew Troelsen
    ASP.NET:性能与缓存
    New Feature In C# 2.0
    .NET Remoting中的通道注册
    通过应用程序域AppDomain加载和卸载程序集
    Some BrainTeaser in WinDev, Can you Solve them?
    ExtJs学习笔记(24)Drag/Drop拖动功能
    wap开发体会
    关于”System.ServiceModel.Activation.WebServiceHostFactory“与"<webHttp/>"以及RestFul/启用了Ajax的WCF服务
    验证码无刷新更换
  • 原文地址:https://www.cnblogs.com/loveapple/p/11150034.html
Copyright © 2011-2022 走看看