• java实现多线程的两种方式


    Java需要并发控制三个原因:

    1. 多线程环境
    2. 存在共享资源
    3. 多个线程操作(修改)共享资源

    下面分别用继承Thread类和实现Runnable接口俩种方式实现并发控制,

    继承Thread类

    继承Thread类方式,最后创建对象是因为会是三个不同的线程对象,所以需要将共享资源和锁都静态化,如果不这样的话,就不存在共享资源一说了,自然也没有并发控制的说法。

    class MyThread extends Thread{
        //电影票总数100张
        private static int ticket=100;
        //锁对象
        private static Object obj = new Object();
    
        @Override
        public void run() {
            while(true){
                synchronized (obj) {                
                if(ticket>0){
                    System.out.println(this.currentThread().getName()+"正在出售第"+ticket--+"张票");
                }
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    public class ThreadDemo {
        public static void main(String[] args) {
            Thread t1 = new MyThread();
            Thread t2 = new MyThread();
            Thread t3 = new MyThread();
            t1.setName("售票员1");
            t2.setName("售票员2");
            t3.setName("售票员3");
            t1.start();
            t2.start();
            t3.start();
        }
    }

    实现Runnable接口

    实现Runnable接口方式,因为构造函数中,需要传入一个Runnable接口类型,所以这里就直接存在共享资源了,静态修饰可有可无,但是还是写上比较好。

    class MyRunnable implements Runnable{
        //电影票总数100张
        private int ticket=100;
        //锁对象
        private Object obj = new Object();
    
        @Override
        public void run() {
            while(true){
                synchronized (obj) {                
                if(ticket>0){
                    System.out.println(Thread.currentThread().getName()+"正在出售第"+ticket--+"张票");
                }
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
            }
        }
    }
    public class RunnableDemo {
        public static void main(String[] args) {
            Runnable r = new MyRunnable();
            Thread t1 = new Thread(r,"售票员1");
            Thread t2 = new Thread(r,"售票员2");
            Thread t3 = new Thread(r,"售票员3");
            t1.start();
            t2.start();
            t3.start();
        }
    }
  • 相关阅读:
    Python pip配置国内源
    【VLC】VLC命令行参数
    发个在owasp上演讲web应用防火墙的ppt
    Tips of Linux C programming
    linux程序调试
    scrapy结合webkit抓取js生成的页面
    Using Internet Explorer from .NET
    http长连接200万尝试及调优
    nginx url解码引发的waf漏洞
    poj 2513
  • 原文地址:https://www.cnblogs.com/gollong/p/9383888.html
Copyright © 2020-2023  润新知