码迷,mamicode.com
首页 > 编程语言 > 详细

java多线程

时间:2021-05-04 16:12:02      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:err   java多线程   获取   rup   read   end   current   LEDE   out   

实现进程的两种方式

  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多线程

标签:err   java多线程   获取   rup   read   end   current   LEDE   out   

原文地址:https://www.cnblogs.com/codegzy/p/14725985.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!