一、线程对象的创建
账户里面一共有1000块钱,男人和女人同时取没人一次取走五块,取20次。
实现Runnable接口
package com.ouc.a302.synchronizeddemo;
public class Account implements Runnable{
private static int money=1000;
private int amount;
public Account(int amount) {
this.amount = amount;
}
public static int getMoney() {
return money;
}
public static void setMoney(int money) {
Account.money = money;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
@Override
public void run() {
try {
withDraw(amount);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void withDraw(int amount) throws InterruptedException {
for (int i = 0; i < 20; i++) {
money=money-amount;
System.out.println(Thread.currentThread().getName()+"--->"+"The account balance is" +"$"+money);
Thread.sleep(1000);
}
System.out.println("amount = " + amount);
}
public static void main(String[] args) {
Account account=new Account(5);
Thread thread1=new Thread(account,"male");
Thread thread2=new Thread(account,"female");
thread1.start();
thread2.start();
}
}
Thread.currentThread().getName() 这一句可查看线程的名称
二、同步锁
1、同步方法
如果直接采用上面这种方法,运行的时候会存在线程安全问题,男人取完5块钱之后,余额本来应该剩下995元,女人再取5元之后,余额应该剩余990元,但是经过实验发现,有时候,男人取完,女人再取,并不会减去男人取走的钱,这就是线程安全问题。
解决方式,就是再取钱的方法上加同步字段—让方法变成同步方法。
package com.ouc.a302.synchronizeddemo;
public class Account extends Thread{
private static int money=1000;
private int amount;
public Account(int amount) {
this.amount = amount;
}
public static int getMoney() {
return money;
}
public static void setMoney(int money) {
Account.money = money;
}
public int getAmount() {
return amount;
}
public void setAmount(int amount) {
this.amount = amount;
}
@Override
public void run() {
try {
withDraw(amount);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public synchronized void withDraw(int amount) throws InterruptedException {
for (int i = 0; i < 20; i++) {
money=money-amount;
System.out.println(Thread.currentThread().getName()+"--->"+"The account balance is" +"$"+money);
Thread.sleep(1000);
}
System.out.println("amount = " + amount);
}
public static void main(String[] args) {
Account account=new Account(5);
Thread thread1=new Thread(account,"male");
Thread thread2=new Thread(account,"female");
thread1.start();
thread2.start();
}
}
同步方法:
public synchronized void withDraw(int amount) throws InterruptedException {
for (int i = 0; i < 20; i++) {
money=money-amount;
System.out.println(Thread.currentThread().getName()+"--->"+"The account balance is" +"$"+money);
Thread.sleep(1000);
}
System.out.println("amount = " + amount);
}
男人取钱的线程执行的时候,女人的线程不能执行,sychronized字段就是把同步方法所在的对象给锁死,第一个线程操作该对象的时候,把门锁死,其他线程只能等第一个线程执行完了之后才能操作对象。
即,同步方法锁掉的对象是this。
2、同步代码块
package com.ouc.a302.synchronizeddemo;
import java.util.concurrent.locks.ReentrantLock;
public class Account {
int money=1000;
public Account() {
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
}
class Amount implements Runnable{
int moneyInHand=0;
Account account;
private final ReentrantLock reentrantLock=new ReentrantLock();
public Amount(Account account) {
this.account = account;
}
@Override
public void run() {
synchronized (account){
while(true){
if (account.money<=0){
break;
}
test();
}
}
}
private void test(){
if (account.money<=0){
System.out.println(Thread.currentThread().getName()+"余额不足");
}else {
moneyInHand=moneyInHand+5;
System.out.println(Thread.currentThread().getName()+"手上有"+moneyInHand);
account.money=account.money-5;
}
}
public static void main(String[] args) {
Account account=new Account();
Amount amountman=new Amount(account);
Amount amountwoman=new Amount(account);
Thread t1=new Thread(amountman,"man");
Thread t2=new Thread(amountwoman,"woman");
t1.start();
t2.start();
}
}
当需要锁住的对象不是同步方法所在的对象时,则可以通过上面的方法采用同步代码块,来锁住相应的对象。
同步方法相当于里面有synchronized(this) 这个同步代码块只不过隐藏了。
3、lock锁
package com.ouc.a302.synchronizeddemo;
import java.util.concurrent.locks.ReentrantLock;
public class Account {
int money = 1000;
public final ReentrantLock reentrantLock = new ReentrantLock();
public Account() {
}
public int getMoney() {
return money;
}
public void setMoney(int money) {
this.money = money;
}
}
class Amount implements Runnable {
int moneyInHand = 0;
Account account;
public Amount(Account account) {
this.account = account;
}
@Override
public void run() {
account.reentrantLock.lock();
while (true) {
if (account.money <= 0) {
break;
}
test();
}
account.reentrantLock.unlock();
}
private void test() {
if (account.money <= 0) {
System.out.println(Thread.currentThread().getName() + "余额不足");
} else {
moneyInHand = moneyInHand + 5;
System.out.println(Thread.currentThread().getName() + "手上有" + moneyInHand);
account.money = account.money - 5;
}
}
public static void main(String[] args) {
Account account = new Account();
Amount amountman = new Amount(account);
Amount amountwoman = new Amount(account);
Thread t1 = new Thread(amountman, "man");
Thread t2 = new Thread(amountwoman, "woman");
t1.start();
t2.start();
}
}
需要锁哪个对象,就把ReentrantLock类定义在哪个类里面。
三、线程通信
1、管程法
package com.ouc.a302.synchronizeddemo;
public class PCTest {
public static void main(String[] args) {
Buffer buffer = new Buffer();
new Product(buffer).start();
new Consumer(buffer).start();
}
}
//生产者
class Product extends Thread {
Buffer buffer;
public Product(Buffer buffer) {
this.buffer = buffer;
}
//生产
@Override
public void run() {
for (int i = 0; i < 100; i++) {
buffer.push(new Anything(i));
System.out.println("生产了" + i + "个产品");
}
}
}
//消费者
class Consumer extends Thread {
Buffer buffer;
public Consumer(Buffer buffer) {
this.buffer = buffer;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("消费了第" + buffer.get() + "个产品");
}
}
}
//缓冲区
class Buffer {
Anything[] anythings = new Anything[10];
int count = 0;
//生产者放入产品
public synchronized void push(Anything anything) {
//容器满了
if (count == anythings.length) {
try {
//通知消费者消费
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
anythings[count] = anything;
count++;
//通知消费者消费
notifyAll();
}
public synchronized int get() {
//容器空了
if (count == 0) {
try {
//通知生产者生产
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
count--;
Anything anything = anythings[count];
//通知生产者生产
notifyAll();
return anything.id;
}
}
class Anything {
int id;
public Anything(int id) {
this.id = id;
}
}
把生产者生产的产品放入缓存区,通知消费者从缓存区把产品拿出来,然后再通知生产者生产。
2、信号灯法
package com.ouc.a302.synchronizeddemo;
public class PCTest {
public static void main(String[] args) {
TV tv = new TV();
new Player(tv).start();
new Watcher(tv).start();
}
}
//演员
class Player extends Thread {
TV tv;
public Player(TV tv) {
this.tv = tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
if (i % 2 == 0) {
this.tv.play("新闻联播播放中");
} else {
this.tv.play("天气预报播放中");
}
}
}
}
//观众
class Watcher extends Thread {
TV tv;
public Watcher(TV tv) {
this.tv = tv;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
tv.watch();
}
}
}
//产品
class TV {
//演员表演,观众等待
//观众观看,演员等待
String voice;//表演的节目
boolean flag = true;
//表演
public synchronized void play(String voice) {
if (!flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("演员表演了" + voice);
//通知观众观看
this.notifyAll();//唤醒
this.voice = voice;
this.flag = !this.flag;
}
//观看
public synchronized void watch() {
if (flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("观看了" + voice);
//通知演员表演
this.notifyAll();
this.flag = !this.flag;
}
}
四、线程池
package com.ouc.a302.synchronizeddemo;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ThreadPoolDemo {
public static void main(String[] args) {
//1.创建线程池
//newFixedThreadPool 参数为线程池大小
ExecutorService executorService= Executors.newFixedThreadPool(10);
executorService.execute(new MyThread());
executorService.execute(new MyThread());
executorService.execute(new MyThread());
executorService.execute(new MyThread());
//2.关闭连接
executorService.shutdown();
}
}
class MyThread implements Runnable{
@Override
public void run() {
for (int i = 0; i < 4; i++) {
System.out.println(Thread.currentThread().getName()+i);
}
}
}