Java学习随笔5:Java多线程编程

1. 线程是程序中单独顺序的控制流,线程本身依靠程序进行运行,线程是程序中的顺序控制流,只能使用分配给程序的资源和环境。

2. 进程是执行中的程序,一个进程可以包含一个或多个线程,但至少要包含一个线程。

3. 单线程是程序中只存在一个线程,实际上主方法就是一个主线程;多线程是在一个程序中运行多个任务,其目的是更好的使用CPU资源。

4. 在Java中,线程的实现有两种:继承Thread类和实现Runnable接口。Thread类是在java.lang包中定义的,继承Thread类必须重写run()方法。

  例1:继承Thread类的线程

class MyThread extends Thread{
    private String name;
    public MyThread(String name){
        this.name = name;
    }
    
    @Override
    public void run() {
        for(int i = 0; i < 10; i++){
            System.out.println(name+":"+i);
        }
        super.run();
    }
}
public class ThreadDemo01 {
    public static void main(String[] args) {
        MyThread t1 = new MyThread("A");
        MyThread t2 = new MyThread("B");
        
        // 线程的启动是通过start方法
        t1.start();
        t2.start();
    }
}

  例2:实现Runnable接口

class MyRunnable implements Runnable{

    private String name;
    public MyRunnable(String name){
        this.name = name;
    }
    
    @Override
    public void run() {
        for(int i = 0; i < 100; i++){
            System.out.println(name+":"+i);
        }
    }
    
}
public class ThreadDemo02 {
    public static void main(String[] args) {
        MyRunnable r1 = new MyRunnable("A");
        MyRunnable r2 = new MyRunnable("B");
        
        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r2);
        
        t1.start();
        t2.start();
    }
}

5. 线程的状态

  (1) 创建状态:准备好了一个多线程的对象

  (2) 就绪状态:调用了start()方法,等待CPU进行调度

  (3) 运行状态:执行run()方法

  (4) 阻塞状态:暂时停止执行,可能将资源交给其他线程使用

  (5) 终止状态:线程销毁

6. 线程的常用方法

  (1) getName():取得线程名称

  (2) currentThread():取得当前线程对象

  (3) isAlive():判断线程是否启动

  (4) join():线程的强制运行

  (5) sleep():线程的休眠

  (6) yield():线程的礼让

  例1:前五种方法的使用:

class RunnableDemo implements Runnable{
    private String name;
    public RunnableDemo(String name){
        this.name = name;
    }
    
    public void run(){
        for(int i = 0; i < 10; i++){
            try {
                // 1s执行一次
                Thread.sleep(1000);
                System.out.println(name+":"+Thread.currentThread().getName());
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}
public class ThreadDemo03 {
    public static void main(String[] args) {
        RunnableDemo rd1 = new RunnableDemo("A");
        Thread t1 = new Thread(rd1);
        //System.out.println(t1.isAlive());
        t1.start();
        //System.out.println(t1.isAlive());
        
        // 强行执行
        for(int i = 0; i < 10; i++){
            if(i > 5){
                try {
                    t1.join();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            System.out.println("主线程:"+i);
        }
        
        RunnableDemo rd2 = new RunnableDemo("B");
        Thread t2 = new Thread(rd2);
        t2.start();
        
    }
}

  其结果为:

主线程:0
主线程:1
主线程:2
主线程:3
主线程:4
主线程:5
A:Thread-0
A:Thread-0
A:Thread-0
A:Thread-0
A:Thread-0
A:Thread-0
A:Thread-0
A:Thread-0
A:Thread-0
A:Thread-0
主线程:6
主线程:7
主线程:8
主线程:9
B:Thread-1
B:Thread-1
B:Thread-1
B:Thread-1
B:Thread-1
B:Thread-1
B:Thread-1
B:Thread-1
B:Thread-1
B:Thread-1

  例2:礼让的使用

class RunnableDemo02 implements Runnable{
    private String name;
    public RunnableDemo02(String name){
        this.name = name;
    }
    
    @Override
    public void run(){
        for(int i = 0; i < 10; i++){
            System.out.println(name+":"+i);
            if(i == 4){
                System.out.println("礼让");
                // 线程的礼让
                Thread.yield();
            }
            
        }
    }
}
public class ThreadDemo04 {
    public static void main(String[] args) {
        RunnableDemo02 r1 = new RunnableDemo02("A");
        RunnableDemo02 r2 = new RunnableDemo02("B");
        Thread t1 = new Thread(r1);
        Thread t2 = new Thread(r2);
        
        t1.start();
        t2.start();
    }
}

7. 线程的优先级,不一定会影响线程的执行顺序

  优先级顺序设置:1-MIN-PRIORITY; 10-MAX-PRIORITY; 5-NORM-PRIORITY,默认值是5。

class RunnableDemo03 implements Runnable{

    @Override
    public void run() {
        for(int i = 0; i < 5; i++){
            try {
                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getName()+":"+i);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
    
}
public class ThreadDemo05 {
    public static void main(String[] args) {
        Thread t1 = new Thread(new RunnableDemo03(),"A");
        Thread t2 = new Thread(new RunnableDemo03(),"B");
        Thread t3 = new Thread(new RunnableDemo03(),"C");
        t1.setPriority(Thread.MIN_PRIORITY);
        t2.setPriority(Thread.NORM_PRIORITY);
        t3.setPriority(Thread.MAX_PRIORITY);
        
        t1.start();
        t2.start();
        t3.start();
    }
}

8. 同步

  例1:同步代码块

class MyThread2 implements Runnable{
    private int ticket = 5;
    public void run(){
        for(int i = 0; i < 10; i++){
            synchronized(this){
                if(ticket > 0){
                    try {
                        Thread.sleep(500);
                        System.out.println(Thread.currentThread().getName()+":"+ticket--);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
public class ThreadDemo06 {
    public static void main(String[] args) {
        MyThread2 m = new MyThread2();
        Thread t1 = new Thread(m);
        Thread t2 = new Thread(m);
        Thread t3 = new Thread(m);
        t1.start();
        t2.start();
        t3.start();
    }
}

  例2:同步方法

class MyThread2 implements Runnable{
    private int ticket = 5;
    public void run(){
        for(int i = 0; i < 10; i++){
            method();
        }
    }
    
    public synchronized void method(){
        if(ticket > 0){
            try {
                Thread.sleep(500);
                System.out.println(Thread.currentThread().getName()+":"+ticket--);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public class ThreadDemo06 {
    public static void main(String[] args) {
        MyThread2 m = new MyThread2();
        Thread t1 = new Thread(m);
        Thread t2 = new Thread(m);
        Thread t3 = new Thread(m);
        t1.start();
        t2.start();
        t3.start();
    }
}

9. 线程的生命周期

原文地址:https://www.cnblogs.com/mengrennwpu/p/4925643.html