线程
Posted FZZ98
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了线程相关的知识,希望对你有一定的参考价值。
线程
创建线程的方式
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
public class CreateThread {
public static void main(String[] args) throws ExecutionException, InterruptedException {
new Thread1().start();
new Thread(new Thread2()).start();
Future<Integer> future = new FutureTask<>(new Thread3());
new Thread((Runnable) future).start();
Integer integer = future.get();
System.out.println(integer);
}
}
class Thread1 extends Thread{
@Override
public void run() {
System.out.println("thread1 run");
}
}
class Thread2 implements Runnable{
@Override
public void run() {
System.out.println("thread2 run");
}
}
class Thread3 implements Callable<Integer>{
final int i=100;
@Override
public Integer call() throws Exception {
System.out.println("thread3 run");
return i;
}
}
ReentrantLock
import java.util.concurrent.locks.ReentrantLock;
public class LockDemo {
public static void main(String[] args) {
BuyTicket station = new BuyTicket();
new Thread(station,"a").start();
new Thread(station,"b").start();
new Thread(station,"c").start();
}
}
class BuyTicket implements Runnable{
private int tickets = 10;
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while(true){
try{
lock.lock();
if (tickets>0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(tickets--);
} else {
break;
}
} finally {
lock.unlock();
}
}
}
}
Synchronized
Sample 01
public class UnsafeStation {
public static void main(String[] args) {
Station station = new Station();
new Thread(station,"Passenger No."+1).start();
new Thread(station,"Passenger No."+2).start();
new Thread(station,"Passenger No."+3).start();
}
}
class Station implements Runnable{
private int nums = 10;
boolean flag = true;
@Override
public void run() {
while(flag){
try {
buyTickets();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private /*synchronized*/ void buyTickets() throws InterruptedException {
synchronized (this){
if (nums<=0){
flag = false;
System.out.println("tickets is run out.");
return;
}
Thread.sleep(100);
System.out.println(Thread.currentThread().getName()+" : buy the No."+(nums--)+" ticket.");
}
}
}
Sample 02
public class UnsafeBank {
public static void main(String[] args) {
Account account = new Account(100,"account");
Drawing you = new Drawing(account,50,"a");
Drawing wife = new Drawing(account,100,"b");
you.start();
wife.start();
}
}
class Account{
int save;
String name;
public Account(int save,String name){
this.save=save;
this.name=name;
}
}
class Drawing extends Thread{
Account account;
int drawMoney;
int nowMoney;
public Drawing(Account account,int drawMoney,String name){
super(name);
this.account=account;
this.drawMoney=drawMoney;
}
@Override
public void run() {
synchronized (account){
if (account.save-drawMoney<0){
System.out.println("money is not sufficient.");
return;
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
account.save-=drawMoney;
nowMoney+=drawMoney;
System.out.println(account.name+"\'s money is "+account.save);
System.out.println(this.getName()+" now you have "+nowMoney+" in hand.");
}
}
}
Sample 03
public class UnsafeList {
public static void main(String[] args) throws InterruptedException {
ArrayList list = new ArrayList();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
synchronized (list){
list.add(Thread.currentThread().getName());
}
}).start();
}
Thread.sleep(5000);
System.out.println(list.size());
}
}
生产者消费者
管程法
public class TestPC1 {
public static void main(String[] args) {
SynContainer container = new SynContainer();
new Producer(container).start();
new Customer(container).start();
}
}
class Chicken{
int id;
public Chicken(int id){
this.id = id;
}
}
class Producer extends Thread{
SynContainer container;
public Producer(SynContainer container){
this.container=container;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
container.push(new Chicken((i+1)));
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Customer extends Thread{
SynContainer container;
public Customer(SynContainer container){
this.container = container;
}
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
Chicken pop = container.pop();
System.out.println("consume no."+pop.id+" chicken.");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class SynContainer{
Chicken[] chickens = new Chicken[10];
int count=0;
public synchronized void push(Chicken chicken) throws InterruptedException {
if (count==chickens.length-1){
this.wait();
}
chickens[count]=chicken;
System.out.println("produce no."+chicken.id+" chicken.");
count++;
this.notifyAll();
}
public synchronized Chicken pop() throws InterruptedException {
if (count==0){
this.wait();
}
count--;
Chicken chicken = chickens[count];
this.notifyAll();
return chicken;
}
}
信号灯法
public class TestPC2 {
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){
tv.play("super mario");
} else {
tv.play("dragon ball");
}
}
}
}
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 {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
this.voice=voice;
System.out.println("play "+voice);
flag=!flag;
notifyAll();
}
public synchronized void watch(){
if (flag){
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("watch "+voice);
flag=!flag;
notifyAll();
}
}
线程池
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestPool {
public static void main(String[] args) {
ExecutorService service = Executors.newFixedThreadPool(10);
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.shutdown();
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
以上是关于线程的主要内容,如果未能解决你的问题,请参考以下文章
JUC并发编程 共享模式之工具 JUC CountdownLatch(倒计时锁) -- CountdownLatch应用(等待多个线程准备完毕( 可以覆盖上次的打印内)等待多个远程调用结束)(代码片段