静态同步函数
来源:互联网 发布:外星人 台式机 知乎 编辑:程序博客网 时间:2024/05/22 00:26
package com.RunnableDemo;
/**
* 同步函数被静态修饰后,它使用是锁是该函数所属类的字节码文件对象:类名.class,该对象的类型是Class。
*
* 静态进入内存时,内存中没有该类的对象,但一定有该类对应的字节码文件对象,这个对象是唯一的。
*
*
*
*
* */
public class ThreadRunnable implements Runnable {
private static int Ticket = 1000;
boolean flag = true;
Object obj = new Object();
@Override
public void run() {
if (flag) {
while (true)
{
synchronized (ThreadRunnable.class)// 锁
{
if (Ticket > 0) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ "__sale__" + Ticket--);
}
}
}
}
else {
while (true) {
show();
}
}
}
// 同步函数用的是所属对象的锁this
public static synchronized void show() {
while (true)
{
if (Ticket > 0) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ "__show__" + Ticket--);
}
}
}
/**
* @param args
*/
public static void main(String[] args) {
ThreadRunnable t = new ThreadRunnable();
Thread t1 = new Thread(t);
Thread t2 = new Thread(t);
Thread t3 = new Thread(t);
Thread t4 = new Thread(t);
t1.start();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t.flag = false;
t2.start();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t3.start();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
t.flag =true;
t4.start();
}
}
0 0
- 静态同步函数
- Java 多线程 静态同步函数
- JAVA多线程静态同步函数
- 多线程五(同步静态函数)
- 同步函数,静态同步函数,同步代码块
- 多线程之静态同步函数/方法
- java 多线程 同步函数 。同步函数的锁 和 静态同步函数的锁
- 同步代码块,同步函数,静态同步函数的锁对象
- 线程中同步函数和静态函数的锁
- JAVA 多线程静态同步函数的锁是class 对象
- java-静态同步函数的锁是Class对象
- 黑马程序员_Java基础[27]_静态同步函数
- java多线程-静态同步函数的锁是Class对象
- 多线程静态同步函数的锁是class 对象
- (多线程-静态同步函数的锁是Class对象)
- JAVA 多线程静态同步函数的锁是class 对象
- 毕向东讲解(摘)—8.静态同步函数
- 验证同步函数(静态与非静态)的锁是否是Object
- 导航树java排序算法
- ubuntu下使用vi是方向键变乱码_退格键不能使用的解决方法
- 同步函数
- Oracle实验一之安装
- 全文检索lucene中文分词的一些总结
- 静态同步函数
- JavaIO流简介
- struts1(14)---validator框架
- 单例模式的两种写法
- 在C#中利用Keep-Alive处理Socket网络异常断开的方法
- 编写更好的CSS
- 关于Maven创建动态 web工程
- Java多态性探悉
- javaweb之jsp+javabean开发模式的web计算器