线程相关代码2

作者: 晨曦_hero | 来源:发表于2017-09-21 22:15 被阅读0次

俩个人吃苹果( 加锁 synchronized 和wait,notify/notifyall一起用 )
public class Text05 {
public static void main(String[] args) {
Runnable3 runnable3 = new Runnable3();
Thread thread = new Thread(runnable3);
thread.start();
Thread thread_b = new Thread(runnable3);
thread_b.start();

}
}
//俩个人吃苹果 俩秒吃一个 100个
class Runnable3 implements Runnable{
int apple = 100; //共享的变量
@Override//重写run方法,子线程执行的方法写在run里面
public void run() {
while (true) {
//锁里面的代码只能有一个线程执行
synchronized (this) {
if (apple>0) {
//加锁
apple--;
System.out.println(Thread.currentThread().getName()+"吃了苹果,剩下"+apple+"个");
//解锁
}else {
break;
}
}
}
}
}
运行结果:谁先抢到谁先吃,随机

方法二的加锁
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Text06 {
public static void main(String[] args) {
Runnable4 runnable4 = new Runnable4();
Thread thread = new Thread(runnable4);
thread.start();
Thread thread1 = new Thread(runnable4);
thread1.start();
}
}
//俩个人吃一个苹果 俩秒吃一个 100
class Runnable4 implements Runnable{
int apple =100;
final Lock lock = new ReentrantLock();
@Override
//重写run方法 子线程执行的方法写在run里面
//public syncgronized void run(){//锁住函数 同一时刻 只能由一个线程来调用
public void run() {
while (true) {
lock.lock();//加锁
if (apple>0) {
apple--;
System.out.println(Thread.currentThread().getName()+"吃了苹果,剩下"+apple+"个");
lock.unlock();//解锁
}else{
break;
}
}
}
}

相关文章

  • 线程相关代码2

    俩个人吃苹果( 加锁 synchronized 和wait,notify/notifyall一起用 )pu...

  • 线程相关代码

    -sleep:睡眠 public class Text01 {public static void main(St...

  • jstack 死锁 死循环 线程阻塞

    1.死循环: 1.jps找出所属进程的pid: 2.使用jstack找到跟代码相关的线程,为main线程,处于ru...

  • python-创建tcp的多任务服务端

    1.导入包 2.主线程代码 3.子线程代码:

  • iOS多线程

    耗时操作:1.网络请求 2.大量运算3.大文件相关4睡眠代码1.不能在主线程中做耗时的操作2.不能在子线程中修改页...

  • python线程、进程知识梳理

    一.python线程 线程用于提供线程相关的操作,线程是应用程序中工作的最小单元。 上述代码创建了10个“前台”线...

  • Java多线程实现方式

    1.继承Thread类创建线程 线程类 测试代码 2.实现Runable接口创建线程 线程类 测试代码 3.使用线...

  • 面试总结

    2、什么情况下会让线程进入死亡状态: 1.线程中的代码执行完毕2.执行线程的代码时抛出异常 3、线程的interr...

  • Linux下Socket编程(二)——多线程封装

    简介 客户端连接后放到线程中运行 Socket相关代码封装 C++线程 这里使用c++11标准的线程库。 编译时候...

  • 线程核心方法-wait

    ①-1、代码演示使用Object的Notify唤醒wait的线程 ①-2、代码演示使用定时等待唤醒wait的线程 ...

网友评论

    本文标题:线程相关代码2

    本文链接:https://www.haomeiwen.com/subject/ipatextx.html