Java多线程及线程安全实现方法解析
程序员文章站
2022-06-03 15:09:02
一、java多线程实现的两种方式1、继承thread/** * * @version: 1.1.0 * @description: 多线程 * @author: wsq * @date: 2020年...
一、java多线程实现的两种方式
1、继承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(); } }
2、实现 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); } }
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。