您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

java同步的使用条件有哪些

2024/3/4 5:46:46发布22次查看
1、为了保持跨线程的正确可见性,必须使用synchronized或volatile。
2、读取可能是另一个线程最终写入的变量。
3、写一个可能被另一个线程读取的变量。
实例
class sellticket implements runnable {private int tickets = 10; public void run() { while (true) {if (tickets > 0)sell();elsereturn;} } public synchronized void sell() {if (tickets > 0) {system.out.println(thread.currentthread().getname() + 卖出第 + tickets + 张票);tickets--;try {thread.sleep(500);} catch (interruptedexception e) {e.printstacktrace();} }}} public class tickettest {public static void main(string args[]) {sellticket t = new sellticket(); new thread(t, 窗口1).start();new thread(t, 窗口2).start();new thread(t, 窗口3).start(); system.out.println(主线程结束); }}
以上就是java同步的使用条件有哪些的详细内容。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product