package com.myh.kb13.t804.service;
/**
* @Description:
* @author:myh
* @date: 2021/8/4 17:11
*/
public class MyAddMute implements Runnable{
private static int numbers=100;
@Override
public void run() {
int tn=Integer.parseInt(Thread.currentThread().getName());
if(tn%2==0){
add();
}else {
mute();
}
}
//同一时间只有一个线程干活 的代码
public synchronized void add(){
numbers++;
System.out.println("当前线程:"+Thread.currentThread().getName()+",加完结果是:"+numbers);
}
public synchronized void mute(){
numbers--;
System.out.println("当前线程:"+Thread.currentThread().getName()+",减完结果是:"+numbers);
}
public static void main(String[] args) {
MyAddMute mau = new MyAddMute();
for (int i = 0; i < 4; i++) {
Thread th=new Thread(mau);
th.setName(i+"");
th.start();
}
}
}
package com.myh.kb13.t804.service;
/**
* @Description:
* @author:myh
* @date: 2021/8/4 15:56
*/
public class MyTest {
public static void main(String[] args) {
// OneToHun oth=new OneToHun();
OneToHun2 oth=new OneToHun2();
for (int i = 1; i <= 100; i += 10) {
Thread thread = new Thread(oth);
thread.setName(i + "");
thread.start();
}
}
}
package com.myh.kb13.t804.service;
/**
* @Description:
* @author:myh
* @date: 2021/8/4 15:50
*/
public class Nums {
int number;
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}
public void add(int n){
number+=n;
}
}
package com.myh.kb13.t804.service;
/**
* @Description:
* @author:myh
* @date: 2021/8/4 15:52
*/
public class OneToHun implements Runnable{
Nums num=new Nums();
@Override
public void run() {
int threadName= Integer.valueOf(Thread.currentThread().getName());
for (int i = threadName; i < threadName + 10; i++) {
synchronized (num){
num.add(i);
System.out.println("当前线程为:"+threadName+",加入"+i+"的值后为:"+num.getNumber());
}
}
}
}
package com.myh.kb13.t804.service;
/**
* @Description:
* @author:myh
* @date: 2021/8/4 16:18
*/
public class OneToHun2 implements Runnable{
private static int numbers;
@Override
public void run() {
int num=0;
int thn= Integer.parseInt(Thread.currentThread().getName());//线程名 1 11 21 31
for (int i = thn; i < thn + 10; i++) {
num+=i;
}
add(num);
}
public synchronized void add(int num){
numbers+=num;
System.out.println("当前线程是:"+Thread.currentThread().getName()+"循环10此后相加结果为:"+numbers);
}
}