一、实现多线程
实现Thread抽象类,实现多线程。
public class demo01 extends Thread {
public void run(){
for (int i = 0; i < 20; i++) {
System.out.println("我在看代码》》》"+i);
}
}
public static void main (String[] args){
demo01 d = new demo01();
d.start();
for (int i = 0; i < 200; i++) {
System.out.println("我先学习多线程》》》》"+i);
}
}
}
使用Runnable接口实现多线程
/**
* 使用Runnable实现多线程,相对于继承Thread类来说,有以下优势:
* 1、适合多个相同程序代码的线程去处理同一资源的情况
* 2、可以避免由于java的单继承特性所带来的局限性
* 3、增强了程序的健壮性,代码能够被多个线程共享,代码与数据是独立的。
* 开发中建议使用Runnable接口实现多线程。
*/
public class runnableTest implements Runnable {
private int ticket = 10;
@Override
public void run() {
while (true){
if(ticket <= 0){
break;
}
try {
Thread.sleep(200);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()+"买到了第"+ticket--+"张票");
}
}
public static void main(String[] args) {
runnableTest ticket = new runnableTest();
new Thread(ticket,"小明").start();
new Thread(ticket,"小红").start();
new Thread(ticket,"黄牛").start();
}
}
二、lambda表达式
public class lambdaTest {
//方式二:静态内部类
static class like2 implements Ilike {
@Override
public void say(String name) {
System.out.println("I love " + name);
}
}
public static void main(String[] args) {
//方式一
Ilike like = new like();
like.say("老张");
//方式二:
Ilike like2 = new like2();
like2.say("阿丹");
//方式三:局部内部类
class like implements Ilike {
@Override
public void say(String name) {
System.out.println("I love " + name);
}
}
Ilike like3 = new like();
like3.say("丹丹");
//方式四:
like = (name) ->{
System.out.println("i love "+name);
};
like.say("张阿丹");
}
}
interface Ilike {
void say(String name);
}
class like implements Ilike {
@Override
public void say(String name) {
System.out.println("I love " + name);
}
}
三、线程停止
public class TestStop implements Runnable{
//标志位
private boolean flag = true;
@Override
public void run() {
int i = 0;
while (flag) {
System.out.println(",线程运行" + 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线程运行"+i);
if (i == 900){
//调用stop方法,停止线程
testStop.stop();
System.out.println("线程停止......");
}
}
}
}
四、线程方法:sleep、yield、jion
public class Testsleep implements Runnable{
@Override
public void run() {
int num = 10;
while(true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(num--);
if(num<=0){
break;
}
}
}
public static void main(String[] args) {
Testsleep testsleep = new Testsleep();
new Thread(testsleep).start();
}
}
public class Testyield implements Runnable{
@Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName()+"线程执行"+i);
if (i == 4){
Thread.yield();
System.out.println(Thread.currentThread().getName()+"线程执行"+i);
}
}
}
public static void main(String[] args) {
Testyield testyield = new Testyield();
new Thread(testyield,"a").start();
new Thread(testyield,"b").start();
}
}
public class Teatjoin implements Runnable{
@Override
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName()+"线程运行"+i);
}
}
public static void main(String[] args) throws InterruptedException {
Teatjoin teatjoin = new Teatjoin();
Thread thread = new Thread(teatjoin,"vip");
thread.start();
for (int i = 0; i < 20; i++) {
System.out.println("main线程运行"+i);
if(i == 18){
thread.join();
}
}
}
}
五、观测线程状态
//线程的状态
public class Teatstate {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(()->{
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println("/");
});
//观察状态
Thread.State state = thread.getState();
System.out.println(state);//new
//观察启动后
thread.start();
state = thread.getState();
System.out.println(state);//run
while(state != Thread.State.TERMINATED){//只要线程不终止
Thread.sleep(100);
state = thread.getState();//更新状态
System.out.println(state);//输出状态
}
}
}
六、线程优先级
/**
* 优先级低只意味着获得调度的概率低,并不是优先级低的就不会被调用。
*/
public class Testpriority {
public static void main(String[] args) {
myPriority mp = new myPriority();
Thread t1 = new Thread(mp);
Thread t2 = new Thread(mp);
Thread t3 = new Thread(mp);
Thread t4 = new Thread(mp);
Thread t5 = new Thread(mp);
//先设置优先级,再启动线程
t1.start();
t2.setPriority(1);
t2.start();
t3.setPriority(Thread.MAX_PRIORITY);//10
t3.start();
t4.setPriority(8);
t4.start();
t5.setPriority(6);
t5.start();
}
}
class myPriority implements Runnable{
@Override
public void run() {
System.out.println(Thread.currentThread().getName()+"-->"+Thread.currentThread().getPriority());
}
}
七、守护线程
public class TestDaemon {
public static void main(String[] args) {
lb lb = new lb();
you z = new you();
Thread thread = new Thread(lb);
thread.setDaemon(true);//设置为守护线程,默认是false
thread.start();
new Thread(z).start();
}
}
//守护
class lb implements Runnable {
@Override
public void run() {
while(true){
System.out.println("我一直在......");
}
}
}
//you
class you implements Runnable{
@Override
public void run() {
for (int i = 0; i < 36500; i++) {
System.out.println("你一直开心......");
}
}
}
八、线程同步
public class Testsyn {
public static void main(String[] args) {
BuyTicket buyTicket = new BuyTicket();
Thread t1 = new Thread(buyTicket,"张三");
Thread t2 = new Thread(buyTicket,"lisi");
Thread t3 = new Thread(buyTicket,"黄牛");
t1.start();
t2.start();
t3.start();
}
}
class BuyTicket implements Runnable{
private int ticletnum = 10;
boolean flag = true;
@Override
public void run() {
while (flag){
try {
buy();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//synchronize 同步方法
public synchronized void buy() throws InterruptedException {
if(ticletnum <= 0){
flag = false;
return;
}
Thread.sleep(200);
System.out.println(Thread.currentThread().getName()+"抢到第"+ticletnum--+"张票");
}
}
死锁
/**
* 多线程访问统一资源时,要考虑数据操作的安全性问题,一定要使用同步操作,可以使用同步方法或者同步代码块
* 过多的同步操作有可能会带来死锁问题,导致程序进入停滞状态。
*/
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;
}
public void run(){
try {
makeup();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
/**
* 一下程序死锁,两个线程都在等待彼此先完成
*/
// public void makeup() throws InterruptedException {
// if(choice == 0){
// synchronized (lipstick){
// System.out.println(this.girlname+"获得口红的锁");
// Thread.sleep(1000);
// synchronized (mirror){
// System.out.println(this.girlname+"获得镜子的锁");
// }
// }
// }else{
// synchronized (mirror){
// System.out.println(this.girlname+"获得镜子的锁");
// Thread.sleep(2000);
// synchronized (lipstick){
// System.out.println(this.girlname+"获得口红的锁");
// }
// }
//
// }
// }
/**
*把代码块拿出来,不抱互相的锁
*/
public void makeup() throws InterruptedException {
if(choice == 0){
synchronized (lipstick){
System.out.println(this.girlname+"获得口红的锁");
Thread.sleep(1000);
}
synchronized (mirror){
System.out.println(this.girlname+"获得镜子的锁");
}
}else{
synchronized (mirror){
System.out.println(this.girlname+"获得镜子的锁");
Thread.sleep(2000);
}
synchronized (lipstick){
System.out.println(this.girlname+"获得口红的锁");
}
}
}
}
lock锁
/**
* ReentrantLock 加锁,lock显式锁,性能更好一点
*/
public class TestLock {
public static void main(String[] args) {
buytickey b = new buytickey();
new Thread(b).start();
new Thread(b).start();
new Thread(b).start();
}
}
class buytickey implements Runnable {
private int ticketnum = 10;
private final ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
while(true){
try{
lock.lock();//加锁
if(ticketnum>0){
Thread.sleep(100);
System.out.println(ticketnum--);
}else{
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
//解锁
lock.unlock();
}
}
}
}
生产者消费者问题
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;
}
//生产
public void run(){
for (int i = 0; i < 20; i++) {
try {
container.push(new Chicken(i));
System.out.println("生产了"+i+"只鸡");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//消费者
class Consumer extends Thread{
synContainer container;
public Consumer(synContainer container){
this.container = container;
}
@Override
public void run() {
for (int i = 0; i < 20; i++) {
try {
System.out.println("消费了"+container.pop().id+"只鸡");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
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) throws InterruptedException {
//如果容器满了,需要等待消费者消费
if(count == chickens.length){
//通知消费者消费,生产等待
this.wait();
}
chickens[count] = 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 TestPool {
public static void main(String[] args) {
//创建服务,创建线程池
//newFixedThreadPool参数是线程池大小
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());
}
}