java多线程

2021/5/2 20:29:07

本文主要是介绍java多线程,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

实现进程的两种方式

  1. 继承Thread类
  2. 实现Runable接口

设置获取线程名

  1. getName()
  2. setName()

设置获取线程优先级

  1. setPriority(优先级大小)
  2. getPriority()

线程控制

  1. sleep() 休眠
  2. setDaemon() 设置守护线程
  3. join() 等待线程
//简单使用多线程
public class MyThreadDemo1 {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        MyThread myThread1 = new MyThread();

        //setname设置线程名
        myThread.setName("Jerry");
        myThread1.setName("Tom");

        //设置线程优先级 获取getPriority
        myThread.setPriority(Thread.MAX_PRIORITY);
        myThread1.setPriority(Thread.NORM_PRIORITY);


        //通过start方法启动线程,JVM会自动调用run方法
        myThread.start();
        myThread1.start();
    }
}

class MyThread extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            //getname获取线程名
            System.out.println(this.getName()+":"+i);
        }
    }
}

public class MyRunableDemo {
    public static void main(String[] args) {
        MyRunable runable = new MyRunable();
        Thread thread = new Thread(runable);
        Thread thread1 = new Thread(runable);

        thread.start();
        thread1.start();
    }
}

class MyRunable implements Runnable{

    @Override
    public void run() {
        for (int i = 0; i < 100; i++) {
            System.out.println(Thread.currentThread().getName()+ ":" + i);
        }
    }
}


package mystring.demo2;

public class ControlThread {
    public static void main(String[] args) {
        //控制线程的3中方法
        //1.join
        //2.setDaemon
        //3.sleep

        MyThread1 t1 = new MyThread1();
        MyThread1 t2 = new MyThread1();
        MyThread1 t3 = new MyThread1();

//        t1.start();
//        try {
//            t1.join();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        }
        Thread.currentThread().setName("haha");

        t2.setDaemon(true);
        t3.setDaemon(true);
        t2.start();
        t3.start();
        for (int i = 0; i < 10; i++) {
            System.out.println(Thread.currentThread().getName() + ":" + i);
        }
    }
}

class MyThread1 extends Thread{
    @Override
    public void run() {
        for (int i = 0; i < 1000; i++) {
            //getname获取线程名
            System.out.println(this.getName()+":"+i);
//            try {
//                Thread.sleep(1000);
//            } catch (InterruptedException e) {
//                e.printStackTrace();
//            }
        }
    }
}



这篇关于java多线程的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程