编程语言
首页 > 编程语言> > java多线程

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,Thread,start,线程,MyThread1,new,多线程,public
来源: https://www.cnblogs.com/codegzy/p/14725985.html