zoukankan      html  css  js  c++  java
  • Java线程总结(二)

    自定义线程的数据可以共享,也可以不共享,这要看具体的实现方式。

    1.不共享数据多线程实现方式:

    public class MyThread  extends Thread{
        private int count = 4;
    
        public MyThread(String threadName){
            this.setName(threadName);
        }
    
        @Override
        public void run(){
            while (count > 0){
                count = count - 1;
                System.out.println("由 " + Thread.currentThread().getName() + " 计算,count = " + count);
                try {
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        }
    
        public static void main(String[] args) {
            MyThread threadA = new MyThread("A");
            MyThread threadB = new MyThread("B");
            MyThread threadC = new MyThread("C");
            threadA.start();
            threadB.start();
            threadC.start();
        }
    }

    执行结果如下:

    从结果上看,每个线程都是都是先打印3,再打印2,然后是1,0。由此可知各个线程都有一份变量count,不受其他线程的干扰。

    2. 共享数据的多线程实现方式

    public class MyThread  extends Thread{
        private int count = 4;
    
        @Override
        public void run(){
            while (count > 0){
                count = count - 1;
                System.out.println("由 " + Thread.currentThread().getName() + " 计算,count = " + count);
                try {
                    Thread.sleep(1000);
                }catch (InterruptedException e){
                    e.printStackTrace();
                }
            }
        }
    
        public static void main(String[] args) {
            MyThread myThread = new MyThread();
            Thread a = new Thread(myThread,"A");
            Thread b = new Thread(myThread,"B");
            Thread c = new Thread(myThread,"C");
            Thread d = new Thread(myThread,"D");
            a.start();
            b.start();
            c.start();
            d.start();
        }
    }

    执行结果如下:

    由结果可知,A,B,C,D四个线程共享变量count

  • 相关阅读:
    一道经典的线程间通信的编程题
    Windows Live Writer代码插件整理
    Squeeze Excitation Module 对网络的改进分析
    IGC(Interleaved Group Convolutions)
    探秘移动网络模型
    sparse_softmax_cross_entropy_with_logits
    四行公式推完神经网络BP
    视觉跟踪:MDnet
    tensorflow API _ 6 (tf.gfile)
    tensorflow API _ 4 (Logging with tensorflow)
  • 原文地址:https://www.cnblogs.com/hujingwei/p/8098103.html
Copyright © 2011-2022 走看看