zoukankan      html  css  js  c++  java
  • java多线程的实现以及如何保持线程安全

    一、java多线程实现的两种方式

    一、继承Thread

    /**
     * 
     * @version: 1.1.0
     * @Description: 多线程
     * @author: wsq
     * @date: 2020年6月8日下午2:25:33
     */
    public class MyThread extends Thread{
    @Override
    public void run() {
        System.out.println("This is the first thread!");
    }
    public static void main(String[] args) {
        MyThread mt = new MyThread();
        mt.start();
    }
    }

    二、实现 Runnable 接口

    public class MultithreadingTest {
    public static void main(String[] args) {
        new Thread(() -> System.out.println("This is the first thread!")).start();
    }
    }

    或者

    public class MyThreadImpl implements Runnable{
    private int count = 5;
        @Override
        public void run() {
            // TODO Auto-generated method stub
            count--;
            System.out.println("Thread"+Thread.currentThread().getName()+"count:"+count);
        }
    }

    二、解决线程不安全问题

    /**
     * 
     * @version: 1.1.0
     * @Description: 测试类
     * @author: wsq
     * @date: 2020年6月8日下午9:27:02
     */
    public class Test {
        public static void main(String[] args) {
            MyThreadImpl myThreadImpl = new MyThreadImpl();
            Thread A = new Thread(myThreadImpl,"A");
            Thread B = new Thread(myThreadImpl,"B");
            Thread C = new Thread(myThreadImpl,"C");
            Thread D = new Thread(myThreadImpl,"D");
            Thread E = new Thread(myThreadImpl,"E");
            A.start();
            B.start();
            C.start();
            D.start();
            E.start();
        }
    }

    打印结果为:

    ThreadBcount:3
    ThreadCcount:2
    ThreadAcount:3
    ThreadDcount:1
    ThreadEcount:0

    B和A共用一个线程,存在线程安全问题

    改成:

    public class MyThreadImpl implements Runnable{
    private int count = 5;
        @Override
      // 使用同步解决线程安全问题
        synchronized public void run() {
            // TODO Auto-generated method stub
            count--;
            System.out.println("Thread"+Thread.currentThread().getName()+"count:"+count);
        }
    }
  • 相关阅读:
    洛谷—— P2234 [HNOI2002]营业额统计
    BZOJ——3555: [Ctsc2014]企鹅QQ
    CodeVs——T 4919 线段树练习4
    python(35)- 异常处理
    August 29th 2016 Week 36th Monday
    August 28th 2016 Week 36th Sunday
    August 27th 2016 Week 35th Saturday
    August 26th 2016 Week 35th Friday
    August 25th 2016 Week 35th Thursday
    August 24th 2016 Week 35th Wednesday
  • 原文地址:https://www.cnblogs.com/mcjhcnblogs/p/13068664.html
Copyright © 2011-2022 走看看