Java(三) 多线程

欢迎关注我的B站账号:卍卍子非鱼卍卍

多线程

Thread

继承Thread类并重写run()方法,通过start()方法启动线程

public class ThreadTest extends Thread {
    private int count = 10;

    public void run() {
        while (true) {
            System.out.println(count + " ");
            if(--count == 0){
                return;
            }
        }
    }

    public static void main(String[] args) {
        new ThreadTest().start();
    }
}

线程休眠

调用sleep()方法使线程休眠,由于sleep()方法的执行可能抛出InterruptedException异常,所以将slee()方法的调用放在try-catch块中

try {
    Thread.sleep(2000); //休眠2秒
} catch(InterruptedException) {
    e.printStackTrace();
}

线程加入

调用join()方法在线程执行过程中加入另一个线程,原线程需等待加入线程执行完毕之后继续执行

public class JoinTest {
    private Thread threadA;
    private Thread threadB;

    public static void main(String[] args) {
        new JoinTest();
    }

    public JoinTest() {
        //使用匿名内部类形式初始化Thread对象
        threadA = new Thread(new Runnable() {
            int count = 0;

            public void run() {
                while(true) {
                    System.out.println(++count);
                    try {
                        Thread.sleep(100);
                        threadB.join();
                    } catch(Exception e) {
                        e.printStackTrace();
                    }
                    if(count == 100) {
                        break;
                    }
                }
            }
        });
        threadA.start();
        threadB = new Thread(new Runnable() {
            int count = 0;

            public void run() {
                while(true) {
                    System.out.println(++count);
                    try {
                        Thread.sleep(100);
                    } catch(Exception e){
                        e.printStackTrace();
                    }
                    if(count == 100) {
                        break;
                    }
                }
            }
        });
    }
}

线程中断

使用stop()方法停止线程已被废除,提倡在run()方法中使用无限循环,添加一个布尔值控制循环终止。

当线程使用sleep()或wait()方法进入就绪状态时,使用Thread类中的interrupt()方法结束线程,此时程序会抛出InterruptedException异常。可以在处理该异常的同时完成线程中断业务处理,如关闭数据库连接,关闭Socket等。

public class InterruptTest {
    Thread thread;

    public class void main(String[] args) {
        new InterruptTest();
    }

    public InterruptTest() {
        thread = new Thread(new Runnable() {
            int count = 0;

            public void run() {
                while(true) {
                    System.out.println(++count);
                    try {
                        thread.sleep(100);
                    } catch(InterruptedException e) {
                        System.out.println("线程中断");
                        break;
                    }
                }
            }
        });
        thread.start();
        thread.interrupt();
    }
}

线程优先级

使用setPriority()方法调整线程优先级,优先级1~10取整数,数字越大优先级越高,若设置的优先级不在该范围内,将产生IllegalArgumentException

public class PriorityTest {
    public PriorityTest() {
        Thread threadA = new Thread(new MyThread());
        Thread threadB = new Thread(new MyThread());
        Thread threadC = new Thread(new MyThread());
        setPriority("threadA", 5, threadA);
        setPriority("threadB", 4, threadB);
        setPriority("threadC", 3, threadC);
    }

    public static void setPriority(String name, int priority, Thread thread) {
        thread.setPriority(priority);   //设置优先级
        thread.setName(name);           //设置线程名
        thread.start();
    }

    public static void main(String[] args) {
        new PriorityTest();
    }

    //定义一个实现Runnable接口的类用于创建线程
    private final class MyThread implements Runnable {
        int count = 0;

        public void run() {
            while(true) {
                System.out.println(++count);
                try {
                    Thread.sleep(100);
                } catch(InterruptedException e) {
                    System.out.println("线程中断");
                }
                if(count == 100){
                    break;
                }
            }
        }
    }
}

线程同步

同步块

使用关键字synchronized建立同步块,在同步块中对共享资源进行操作

public class ThreadSafeTest implements Runnable {
    int num = 10;

    public void run() {
        while(true) {
            //同步块
            synchronized("") {
                if(num > 0) {
                    try {
                        Thread.sleep(100);
                    } catch(Exception e) {
                        e.printStackTrace();
                    }
                    System.out.println(--num);
                }
            }
        }
    }

    public static void main(String[] args) {
        ThreadSafeTest test = new ThreadSafeTest();
        Thread threadA = new Thread(test);
        Thread threadB = new Thread(test);
        Thread threadC = new Thread(test);
        threadA.start();
        threadB.start();
        threadC.start();
    }
}

同步方法

在方法之前使用关键字synchronized进行修饰,将共享资源的操作写在同步方法中

public class ThreadSafeTest implements Runnable {
    int num = 10;

    public void run() {
        while(true) {
            safe();
        }
    }

    //同步方法
    public synchronized void safe() {
        if(num > 0) {
            try {
                Thread.sleep(100);
            } catch(Exception e) {
                e.printStackTrace();
            }
            System.out.println(--num);
        }
    }

    public static void main(String[] args) {
        ThreadSafeTest test = new ThreadSafeTest();
        Thread threadA = new Thread(test);
        Thread threadB = new Thread(test);
        Thread threadC = new Thread(test);
        threadA.start();
        threadB.start();
        threadC.start();
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值