关于多线程共享资源的方式

package com.joker.threads.demo.thread.mainsub;


/**
 * 多线程共享数据的方法
 * @author GQ 
 */
public class MuiltThreadTest {
private static int j;


public static void main(String[] args) {
MuiltThreadTest test = new MuiltThreadTest();
/**
* 代码不同的时候的实现
*/
AddThread addThread =test.new AddThread();
ReduceThread reduceThread = test.new ReduceThread();
for(int i=0;i<10;i++) {
reduceThread.run();
reduceThread.run();
addThread.run();
addThread.run();
}
/**
* 代码相同时候的实现
* 多线程共享数据 总结:如果线程代码相同,则使用同一个线程类,线程类中包含有共享数据
*/
// int c = ticketOffice.getCount();
// for (int i = 0; i < 10; i++) {
// TicketOffice ticketOffice = test.new TicketOffice();
// while (ticketOffice.getCount() > 0) {
// new Thread(ticketOffice).start();
// new Thread(ticketOffice).start();
// new Thread(ticketOffice).start();
// new Thread(ticketOffice).start();
// new Thread(ticketOffice).start();
// }
// System.out.println("票已经卖完");
// }
}
/**

* 代码不同时的实现
* 使用内部类进行操作
*
*/
class AddThread implements Runnable {
public synchronized void reduceJ() {
j--;
System.out.println(j);
}


@Override
public void run() {
reduceJ();
}


}


class ReduceThread implements Runnable {
public synchronized void addJ() {
j++;
System.out.println(j);
}


@Override
public void run() {
addJ();
}
}


class TicketOffice implements Runnable {
public int getCount() {
return count;
}


public void setCount(int count) {
this.count = count;
}


private int count = 10;


@Override
public void run() {
sellTicket();
}


public synchronized void sellTicket() {
while (count > 0) {
count--;
System.out.println("还剩余票数为:" + count);
}
}


}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值