如不雅加上synchronized关键字,则会先输出一组0到9,然后再输出下一组,解释两个线程是按序履行的。
多线程的同步机制对资本进行加锁,使得在同一个时光,只有一个线程可以进行操作,同步用以解决多个线程同时拜访时可能出现的问题。
同步机制可以应用synchronized关键字实现。
当synchronized关键字润饰一个办法的时刻,该办法叫做同步办法。
当synchronized办法履行完或产生异常时,会主动释放锁。
下面经由过程一个例子来对synchronized关键字的用法进行解析。
1,是否应用synchronized关键字的不合
- public class ThreadTest
- {
- public static void main(String[] args)
- {
- Example example = new Example();
- Thread t1 = new Thread1(example);
- Thread t2 = new Thread1(example);
- t1.start();
- t2.start();
- }
- }
- class Example
- {
- public synchronized void execute()
- {
- for (int i = 0; i < 10; ++i)
- {
- try
- {
- Thread.sleep(500);
- }
- catch (InterruptedException e)
- {
- e.printStackTrace();
- }
- System.out.println("Hello: " + i);
- }
- }
- }
- class Thread1 extends Thread
- {
- private Example example;
- public Thread1(Example example)
- {
- this.example = example;
- }
- @Override
推荐阅读
惯例的筹划: 用Golang写一个http/TCP办事,php经由过程http/TCP与Golang通信 将Golang经由较多封装,做为php扩大。 PHP经由过程体系敕令,调取Golang的可履行文件存在的问题: >>>详细阅读
本文标题:Java多线程之synchronized关键字详解
地址:http://www.17bianji.com/lsqh/35484.html
1/2 1