Java 多线程基础
实现方式
Runnable 接口
package com.hzl.duoxiancheng.Runnable;
public class MyRunnable implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("running");
}
}
}
package com.hzl.duoxiancheng.Runnable;
public class MainTest {
public static void main(String[] args) {
MyRunnable instance = new MyRunnable();
Thread thread = new Thread(instance);
thread.start();
}
}
Callable
package com.hzl.duoxiancheng.Callable;
import java.util.concurrent.Callable;
public class MyCallable implements Callable {
@Override
public Object call() throws Exception {
for (int i = 0; i < 100; i++) {
System.out.println("calling");
}
return "thread run end";
}
}
package com.hzl.duoxiancheng.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class MainTest {
public static void main(String[] args) throws ExecutionException, InterruptedException {
MyCallable myCallable = new MyCallable();
FutureTask futureTask = new FutureTask<>(myCallable);
Thread thread = new Thread(futureTask);
thread.start();
System.out.println(futureTask.get());
}
}
继承 Thread 类
public class MyThread extends Thread {
public void run() {
// ...
}
}
https://pdai.tech/md/java/thread/java-thread-x-thread-basic.html#sleep
生命周期

同步代码块
package com.hzl.learn.A03BingFa.A01ChangJing;
import java.util.Timer;
public class Main {
public static void main(String[] args) {
class Count implements Runnable{
static int count = 0;
static Object obj= new Object();
@Override
public void run() {
while (true){
synchronized (obj){
if(count<1000){
try {
Thread.sleep(20);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
count++;
System.out.println(Thread.currentThread().getName()+"正在卖第"+count+"张票");
}
}
}
}
}
Count count = new Count();
new Thread(count).start();
new Thread(count).start();
new Thread(count).start();
}
}
lock

package com.hzl.learn.A03BingFa.A01ChangJing;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class LockTest {
public static void main(String[] args) {
class Count implements Runnable{
static int count = 0;
// static Object obj= new Object();
static Lock lock = new ReentrantLock();
@Override
public void run() {
while (true){
// synchronized (obj){
lock.lock();
if(count<1000){
try {
Thread.sleep(20);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
count++;
System.out.println(Thread.currentThread().getName()+"正在卖第"+count+"张票");
}else {
lock.unlock();
break; }
// }
lock.unlock();
}
}
}
Count count = new Count();
new Thread(count).start();
new Thread(count).start();
new Thread(count).start();
}
}
等待唤醒

package com.hzl.learn.A03BingFa.A01ChangJing;
import java.util.LinkedList;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class WaitTest {
public static void main(String[] args) {
// 保证同一时间只有一个线程访问 buffer Object BufferLock = new Object();
// 存放的队列
LinkedList<String> strings = new LinkedList<>();
class Consumer implements Runnable{
@Override
public void run() {
while (true){
// 生产者和消费者同时修改 buffer, 枷锁
synchronized (BufferLock){
if (strings.isEmpty()){
try {
BufferLock.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}else{
String s = strings.removeLast();
System.out.println("消费者消费:\t"+s);
// 已经有空位了, 唤醒生产者
BufferLock.notifyAll();
}
}
}
}
}
class Producer implements Runnable{
private int maxCount = 100;
private int itemIndex = 0;
@Override
public void run() {
while (true){
if(itemIndex>maxCount) break;
synchronized (BufferLock){
if(strings.size()==10){
try {
BufferLock.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}else {
String s = "item--"+itemIndex;
itemIndex++;
strings.addLast(s);
BufferLock.notifyAll();
}
}
}
System.out.println("生产者停止了工作---------");
}
}
new Thread(new Consumer()).start();
new Thread(new Producer()).start();
}
}
基于 信号量的同步问题
package com.hzl.learn.A03BingFa.A01ChangJing;
import java.util.LinkedList;
import java.util.concurrent.Semaphore;
public class XinHaoLiang {
/**
* 基于信号量的 生产者消费者
*/
public static void main(String[] args) {
Semaphore empty = new Semaphore(5); //剩余位置
Semaphore mutex = new Semaphore(1); // 互斥信号量, 控制并发访问
Semaphore isFilled = new Semaphore(0); // 控制生产者是否生产
LinkedList<String> strings = new LinkedList<>(); // 存放队列
class Consumer implements Runnable{
@Override
public void run() {
while (true){
// 请求一个有货物的位置
try {
isFilled.acquire();
mutex.acquire();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
String s = strings.removeLast();
System.out.println("消费者消费:\t"+s);
mutex.release();
// 消费了一个, 所以empty++
empty.release();
}
}
}
class Producer implements Runnable{
private int itemIndex = 0;
private int maxCount =100;
@Override
public void run() {
while (itemIndex<maxCount){
// 生产者生产, 请求一个空位存放货物
try {
empty.acquire();
mutex.acquire();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
String s = "item--"+itemIndex;
itemIndex++;
strings.addLast(s);
mutex.release();
// 存有的数量 ++ isFilled.release();
}
System.out.println("生产者停止了工作");
}
}
new Thread(new Producer()).start();
new Thread(new Consumer()).start();
}
}