并发编程

This commit is contained in:
罗祥
2019-11-24 08:37:29 +08:00
parent 910790be8c
commit 5333702053
6 changed files with 227 additions and 34 deletions

View File

@ -0,0 +1,16 @@
package com.heibaiying.createThread;
public class J1_Method01 {
public static void main(String[] args) {
System.out.println("Main线程的ID为" + Thread.currentThread().getId());
Thread thread = new Thread(new CustomRunner());
thread.start();
}
}
class CustomRunner implements Runnable {
@Override
public void run() {
System.out.println("CustomThread线程的ID为" + Thread.currentThread().getId());
}
}

View File

@ -0,0 +1,16 @@
package com.heibaiying.createThread;
public class J2_Method02 {
public static void main(String[] args) {
System.out.println("Main线程的ID为" + Thread.currentThread().getId());
CustomThread customThread = new CustomThread();
customThread.start();
}
}
class CustomThread extends Thread {
@Override
public void run() {
System.out.println("CustomThread线程的ID为" + Thread.currentThread().getId());
}
}

View File

@ -0,0 +1,34 @@
package com.heibaiying.threeCharacteristics;
/**
* 竞态
*/
public class J1_RaceCondition {
private static int i = 0;
public static void main(String[] args) throws InterruptedException {
IncreaseTask task = new IncreaseTask();
Thread thread1 = new Thread(task);
Thread thread2 = new Thread(task);
thread1.start();
thread2.start();
//等待线程结束后 才打印返回值
thread1.join();
thread2.join();
System.out.println(i);
}
static class IncreaseTask implements Runnable {
@Override
public void run() {
for (int j = 0; j < 100000; j++) {
inc();
}
}
private void inc() {
i++;
}
}
}

View File

@ -0,0 +1,36 @@
package com.heibaiying.threeCharacteristics;
import java.util.concurrent.atomic.AtomicInteger;
/**
* 原子性
*/
public class J2_Atomic {
private static AtomicInteger i = new AtomicInteger(0);
public static void main(String[] args) throws InterruptedException {
IncreaseTask task = new IncreaseTask();
Thread thread1 = new Thread(task);
Thread thread2 = new Thread(task);
thread1.start();
thread2.start();
//等待线程结束后 才打印返回值
thread1.join();
thread2.join();
System.out.println(i);
}
static class IncreaseTask implements Runnable {
@Override
public void run() {
for (int j = 0; j < 100000; j++) {
inc();
}
}
private void inc() {
i.incrementAndGet();
}
}
}