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();
    }

}

 

posted @ 2019-07-08 11:18  小白2510  阅读(350)  评论(0编辑  收藏  举报