public class TestThread1 extends Thread{
@Override
public void run() {
for (int i = 0;i < 20;i++){
System.out.println("我不是主线程");
}
}
public static void main(String[] args) {
//创建线程对象
TestThread1 testThread1 = new TestThread1();
//调用start()方法开启线程
testThread1.start();
for (int i =0; i< 1000; i++){
System.out.println("主线程");
}
}
}

线程不一定立即执行,CPU安排调度
推荐使用Runnable对象.因为Java单继承的局限性
public class TestThread3 implements Runnable {
@Override
public void run() {
for (int i = 0;i < 20;i++){
System.out.println("我不是主线程");
}
}
public static void main(String[] args) {
//创建Runnable接口的实现类对象
TestThread3 testThread3 = new TestThread3();
//创建线程对象,通过线程对象开启线程,代理
Thread thread = new Thread(testThread3);
thread.start();
for (int i =0; i< 1000; i++){
System.out.println("主线程");
}
}
}

1.实现Callable接口,需要返回值类型
2.重写call方法,需要抛出异常
3.创建目标对象
4.创建执行服务:ExecutorService ser = Executors.newFixedThreadPool(1);
5.提交执行:Future result1 = ser.submit(t1);
6.获取结果: boolean r1 = result1.get()
7.关闭服务:ser.shutdownNow();
public class TestThread4 implements Runnable{
//票数
private int ticketNums = 10;
@Override
public void run() {
while (true) {
if (ticketNums<=0){
break;
}
//模拟延时
try {
Thread.sleep(200);
}catch (InterruptedException e) {
e.printStackTrace();
}
//currentThread()代表当前线程 getName()获取线程名
System.out.println(Thread.currentThread().getName()+"抢到了第"+ticketNums--+"号票");
}
}
public static void main(String[] args) {
TestThread4 ticket = new TestThread4();
new Thread(ticket,"肥皂").start();
new Thread(ticket,"幽灵").start();
new Thread(ticket,"普莱斯").start();
}
}
结果出现并发问题,两个人抢到了同一张票,线程不安全

public class StacticProxy {
public static void main(String[] args) {
WeddingCompany weddingCompany = new WeddingCompany(new You());
weddingCompany.HappyMarry();
}
}
//结婚的规范(接口),需要快乐
interface Marry{
void HappyMarry();
}
//真实角色,你去结婚
class You implements Marry{
@Override
public void HappyMarry() {
System.out.println("你要结婚了,新浪不是我");
}
}
//代理角色,帮助你结婚(婚庆公司)
class WeddingCompany implements Marry{
private Marry target;
public WeddingCompany(Marry target){
this.target = target;
}
@Override
public void HappyMarry() {
before();
this.target.HappyMarry();
after();
}
private void before(){
System.out.println("婚前布置");
}
private void after(){
System.out.println("婚后收钱");
}
}

静态代理模式总结;
优点:


public class TestStop implements Runnable{
//设置标识位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag){
System.out.println("run-Thread"+i++);
}
}
public void stop(){
this.flag = false;
}
public static void main(String[] args) {
TestStop testStop = new TestStop();
new Thread(testStop).start();
for (int i = 0; i < 1000; i++) {
System.out.println("main线程开始跑了");
if (i==900){
//调用stop方法切换标志位,让线程停止
testStop.stop();
System.out.println("该线程已被停止!!!!");
}
}
}
}

public class TestYield {
public static void main(String[] args) {
MyYield myYield = new MyYield();
new Thread(myYield,"a").start();
new Thread(myYield,"b").start();
}
}
class MyYield implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"线程开始");
Thread.yield();//礼让
System.out.println(Thread.currentThread().getName()+"线程停止");
}
}

Join合并线程,待此线程执行完成后,再执行其他线程,其他线程阻塞
public class TestJoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println("VIP来辣!!!");
}
}
public static void main(String[] args) throws InterruptedException{
//启动线程
TestJoin testJoin = new TestJoin();
Thread thread = new Thread(testJoin);
thread.start();
//主线程
for (int i = 0; i < 500; i++) {
if (i == 200){
thread.join();//插队
}
System.out.println("main" + i);
}
}
}


如何观测:

Java提供一个线程调度器来监控程序中启动后进入就绪状态的所有线程,线程调度器按照优先级决定应该调度哪个线程来执行。
线程的优先级用数字表示,范围从1~10.
使用以下方式改变或获取优先级
getPriority() . setPriority(int xxx)
源码看线程的优先级
如何使用
处理多线程问题时﹐多个线程访问同一个对象﹐并且某些线程还想修改这个对象.这时候我们就需要线程同步﹒线程同步其实就是一种等待机制,多个需要同时访问此对象的线程进入这个对象的等待池形成队列,等待前面线程使用完毕,下一个线程再使用
由于同一进程的多个线程共享同一块存储空间,在带来方便的同时,也带来了访问冲突问题,为了保证数据在方法中被访问时的正确性,在访问时加入锁机制synchronized , 当一个线程获得对象的排它锁,独占资源﹐其他线程必须等待,使用后释放锁即可.存在以下问题:
- 一个线程持有锁会导致其他所有需要此锁的线程挂起;
- 在多线程竞争下,加锁﹐释放锁会导致比较多的上下文切换和调度延时,引起性能问题;
- 如果一个优先级高的线程等待一个优先级低的线程释放锁会导致优先级倒置,引起性能问题.
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket station = new BuyTicket();
new Thread(station,"肥皂").start();
new Thread(station,"幽灵").start();
new Thread(station,"普莱斯").start();
}
}
class BuyTicket implements Runnable{
//票
private int ticketNums = 10;
boolean flag = true;//外部停止方式
@Override
public void run() {
//买票
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void buy() throws InterruptedException {
//判断是否有票
if (ticketNums<=0){
flag = false;
return;
}
//模拟演示
Thread.sleep(100);
//买票
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
}

public class UnsafeBank {
public static void main(String[] args) {
//账户一共100
Account account = new Account(100,"资金");
//你取50,他取100
Drawing no1 = new Drawing(account,50,"一号");
Drawing no2 = new Drawing(account,100,"二号");
no1.start();
no2.start();
}
}
//账户
class Account{
int money; //余额
String name; //卡名
public Account(int money, String name) {
this.money = money;
this.name = name;
}
}
//银行
class Drawing extends Thread{
Account account; //账户
//取了多少钱
int drawingMoney;
//剩余
int nowMoney;
public Drawing(Account account,int drawingMoney,String name){
super(name);//调用父类有参构造方法,传名字
this.account = account;
this.drawingMoney = drawingMoney;
}
//取钱
@Override
public void run() {
//判断是否有钱
if (account.money-drawingMoney<0){
System.out.println(Thread.currentThread().getName()+"钱不够");
return;
}
//进来没取钱,先堵塞
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额=余额 - 你娶的前
account.money = account.money - drawingMoney;
//你手里的钱
nowMoney = nowMoney + drawingMoney;
System.out.println(account.name+"余额为:"+account.money);
//这里的this指代Thread
System.out.println(this.getName()+"手里的钱:"+nowMoney);
}
}

import java.util.ArrayList;
import java.util.List;
public class UnsafeList {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
System.out.println(list.size());
}
}

因为:可能两个线程同一瞬间把两个数组添加到同一位置
思路
同步块
synchronized同步方法,默认锁的是this
public class UnsafeBuyTicket {
public static void main(String[] args) {
BuyTicket station = new BuyTicket();
new Thread(station,"肥皂").start();
new Thread(station,"幽灵").start();
new Thread(station,"普莱斯").start();
}
}
class BuyTicket implements Runnable{
//票
private int ticketNums = 10;
boolean flag = true;//外部停止方式
@Override
public void run() {
//买票
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//synchronized同步方法,默认锁的是this
private synchronized void buy() throws InterruptedException {
//判断是否有票
if (ticketNums<=0){
flag = false;
return;
}
//模拟演示
Thread.sleep(100);
//买票
System.out.println(Thread.currentThread().getName()+"拿到"+ticketNums--);
}
}
共享资源account为同步监视器
public class UnsafeBank {
public static void main(String[] args) {
//账户一共100
Account account = new Account(100,"资金");
//你取50,他取100
Drawing no1 = new Drawing(account,50,"一号");
Drawing no2 = new Drawing(account,100,"二号");
no1.start();
no2.start();
}
}
//账户
class Account{
int money; //余额
String name; //卡名
public Account(int money, String name) {
this.money = money;
this.name = name;
}
}
//银行
class Drawing extends Thread{
Account account; //账户
//取了多少钱
int drawingMoney;
//剩余
int nowMoney;
public Drawing(Account account,int drawingMoney,String name){
super(name);//调用父类有参构造方法,传名字
this.account = account;
this.drawingMoney = drawingMoney;
}
//取钱
@Override
public void run() { //锁run没用
//共享资源account为同步监视器
synchronized (account){
//判断是否有钱
if (account.money-drawingMoney<0){
System.out.println(Thread.currentThread().getName()+"钱不够");
return;
}
//进来没取钱,先堵塞
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//卡内余额=余额 - 你娶的前
account.money = account.money - drawingMoney;
//你手里的钱
nowMoney = nowMoney + drawingMoney;
System.out.println(account.name+"余额为:"+account.money);
//这里的this指代Thread
System.out.println(this.getName()+"手里的钱:"+nowMoney);
}
}
}
要往list里添加数据,list为共享数据,为同步监视器
import java.util.ArrayList;
import java.util.List;
public class UnsafeList {
public static void main(String[] args) {
List<String> list = new ArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
//要往list里添加数据,list为共享数据
synchronized (list){
list.add(Thread.currentThread().getName());
}
}).start();
}
System.out.println(list.size());
}
}
多个线程各自占有一些共享资源﹐并且互相等待其他线程占有的资源才能运行﹐而导致两个或者多个线程都在等待对方释放资源﹐都停止执行的情形.某一个同步块同时拥有“两个以上对象的锁”时,就可能会发生“死锁”的问题.
产生死锁的四个必要条件:
死锁演示
//死锁:多个线程互相拿着对方需要的资源,然后形成僵持.
public class DeadLock {
public static void main(String[] args) {
Makeup g1 = new Makeup(0,"女主");
Makeup g2 = new Makeup(1,"女配");
g1.start();
g2.start();
}
}
//口红
class Lipstick{
}
//镜子
class Mirror{
}
//化妆
class Makeup extends Thread {
//需要的资源只有一份,用静态static来保证
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choice;//选择
String girlName;//使用口红的人
Makeup(int choice, String girlName) {
this.choice = choice;
this.girlName = girlName;
}
@Override
public void run() {
//化妆
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//化妆,互相持有对方的锁,就是需要拿到对方的资源
//一个拿口红锁,另一个人拿镜子锁,然后谁都无法进行下一步
private void makeup() throws InterruptedException {
if (choice == 0) {
synchronized (lipstick) { //获得口红的锁
System.out.println(this.girlName + "获得口红的锁");
Thread.sleep(1000);
synchronized (mirror) { //sleep后想获得镜子
System.out.println(this.girlName + "获得镜子的锁");
}
}
} else {
synchronized (mirror) { //获得口红的锁
System.out.println(this.girlName + "获得镜子的锁");
Thread.sleep(2000);
synchronized (lipstick) { //sleep后想获得镜子
System.out.println(this.girlName + "获得口红的锁");
}
}
}
}
}
卡住了

//死锁:多个线程互相拿着对方需要的资源,然后形成僵持.
public class DeadLock {
public static void main(String[] args) {
Makeup g1 = new Makeup(0,"女主");
Makeup g2 = new Makeup(1,"女配");
g1.start();
g2.start();
}
}
//口红
class Lipstick{
}
//镜子
class Mirror{
}
//化妆
class Makeup extends Thread {
//需要的资源只有一份,用静态static来保证
static Lipstick lipstick = new Lipstick();
static Mirror mirror = new Mirror();
int choice;//选择
String girlName;//使用口红的人
Makeup(int choice, String girlName) {
this.choice = choice;
this.girlName = girlName;
}
@Override
public void run() {
//化妆
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//化妆,互相持有对方的锁,就是需要拿到对方的资源
//一个拿口红锁,另一个人拿镜子锁,然后谁都无法进行下一步
private void makeup() throws InterruptedException {
if (choice == 0) {
synchronized (lipstick) { //获得口红的锁
System.out.println(this.girlName + "获得口红的锁");
Thread.sleep(1000);
}
synchronized (mirror) { //sleep后想获得镜子
System.out.println(this.girlName + "获得镜子的锁");
}
} else {
synchronized (mirror) { //获得口红的锁
System.out.println(this.girlName + "获得镜子的锁");
Thread.sleep(2000);
}
synchronized (lipstick) { //sleep后想获得镜子
System.out.println(this.girlName + "获得口红的锁");
}
}
}
}

应用场景∶



//测试:生产者消费者模型-->利用缓冲区解决:管程法
public class TestPC {
public static void main(String[] args) {
SynContainer container = new SynContainer();
new Productor(container).start();
new Consumer(container).start();
}
}
//生产者
class Productor extends Thread{
SynContainer container;
public Productor(SynContainer container){
this.container = container;
}
//生产
@Override
public void run() {
for (int i = 0; i < 100; i++) {
container.push(new Chicken(i));
System.out.println("生产了第"+i+"只鸡");
}
}
}
//消费者
class Consumer extends Thread{
SynContainer container;
public Consumer(SynContainer container){
this.container = container;
}
//消费
@Override
public void run() {
for (int i = 0; i < 100; i++) {
System.out.println("消费了第"+container.pop().id+"只鸡");
}
}
}
//产品
class Chicken{
int id; //产品编号
public Chicken(int id) {
this.id = id;
}
}
//缓冲区
class SynContainer{
//需要一个容器大小
Chicken[] chickens = new Chicken[10];
//容器计数器
int count = 0;
//生产者放入产品
public synchronized void push(Chicken chicken){
//如果容器满了,就需要等待消费者消费
if (count==chickens.length){
//通知消费者消费,生产等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果没有满。我们就需要丢入产品
chickens[count]=chicken;
count++;
//可以通知消费者消费了
this.notifyAll();
}
//消费者消费产品
public synchronized Chicken pop(){
//判断是否能消费
if (count==0){
//等待生产者生产,消费者等待
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//如果可以消费
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){
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;
}
}

import java.util.concurrent.CopyOnWriteArrayList;
//测试JUC安全类型的集合
public class TestJUC {
public static void main(String[] args) {
CopyOnWriteArrayList<String> list = new CopyOnWriteArrayList<String>();
for (int i = 0; i < 10000; i++) {
new Thread(()->{
list.add(Thread.currentThread().getName());
}).start();
}
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(list.size());
}
}

Lock
如果同步代码有异常,要将unlock()写入finally语句块
import java.util.concurrent.locks.ReentrantLock;
public class TestLock {
public static void main(String[] args) {
TestLock2 testLock2 = new TestLock2();
//跑三个线程
new Thread(testLock2).start();
new Thread(testLock2).start();
new Thread(testLock2).start();
}
}
class TestLock2 implements Runnable{
int ticketNums = 10;
//定义Lock锁
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while (true){
try {
lock.lock(); //加锁
if (ticketNums>0){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(ticketNums--);
}else{
break;
}
}finally { //如果同步代码有异常,要将unlock()写入finally语句块
lock.unlock();//解锁
}
}
}
}

* JDK 5.0起提供了线程池相关API: ExecutorService和* ExecutorsExecutorService:真正的线程池接口。常见子类ThreadPoolExecuutor
* void execute(Runnable command):执行任务/命令,没有返回值,一般用来执行Runnable
* Future submit(Callable task):执行任务,有返回值,一般又来执行Callable
* void shutdown():关闭连接池
* Executors:工具类、线程池的工厂类,用于创建并返回不同类型的线程池
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class TestPool {
public static void main(String[] args) {
//1.创建服务,创建线程池
//newFixedThreadPool 参数为:线程池大小
ExecutorService service = Executors.newFixedThreadPool(10);
//执行
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
service.execute(new MyThread());
//2.关闭链接
service.shutdown();
}
}
class MyThread implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
}
