是否在execute()办法前加上synchronized关键字,这个例子法度榜样的履行结不雅会有很大年夜的不合。
如不雅不加synchronized关键字,则两个线程同时履行execute()办法,输出是两组并发的。
2.多个办法的多线程情况
将法度榜样修改一下,Example类中再参加一个办法execute2()。
之后再写一个线程类Thread2,Thread2中的run()办法履行的是execute2()。Example类中的两个办法都是被synchronized关键字润饰的。
如许就可以自行规定上锁对象。
- public class ThreadTest
- {
- public static void main(String[] args)
- {
- Example example = new Example();
- Thread t1 = new Thread1(example);
- Thread t2 = new Thread2(example);
- t1.start();
- t2.start();
- }
- }
- class Example
- {
- public synchronized void execute()
- {
- for (int i = 0; i < 20; ++i)
- {
- try
- {
- Thread.sleep((long) Math.random() * 1000);
- }
- catch (InterruptedException e)
- {
- e.printStackTrace();
- }
- System.out.println("Hello: " + i);
- }
- }
- public synchronized void execute2()
- {
- for (int i = 0; i < 20; ++i)
- {
- try
- {
推荐阅读
惯例的筹划: 用Golang写一个http/TCP办事,php经由过程http/TCP与Golang通信 将Golang经由较多封装,做为php扩大。 PHP经由过程体系敕令,调取Golang的可履行文件存在的问题: >>>详细阅读
本文标题:Java多线程之synchronized关键字详解
地址:http://www.17bianji.com/lsqh/35484.html
1/2 1