【JavaThread】


案例引入


public class demo0 {
    /*
    此程序只能按照从上向下的顺序执行,
    因为是单线程的,只有main这一个线程
     */
    public static void main(String[] args) {
        System.out.println("main开始执行");

        methodA();
        methodB();

        System.out.println("main结束执行");
    }

    public static void methodA(){
        System.out.println("methodA");
    }
    public static void methodB(){
        System.out.println("methodB");
    }
}


Thread类中的方法


import javax.sound.midi.Soundbank;

public class ThreadTest {
    public static void main(String[] args) {
        /*
        Thread类中的方法
          run(); 用来定义线程要执行的任务代码
          start();
          currentThread();获取当前线程
          getId();获取当前线程Id
          setName();为线程设置名字
          getPriority();获取线程的优先级
          setPriority();设置线程优先级 优先级为1-10 默认是5 作用是为系统调度算法提供的
          getName();获取线程名字
         */
        com.ffyc.javaThread.demo2.MyThread myThread = new com.ffyc.javaThread.demo2.MyThread();
        System.out.println(myThread.getState());
        myThread.setName("窗口1");
        myThread.setPriority(10);
        myThread.start();
        MyThread myThread1 = new MyThread();
        myThread1.setName("窗口2");
        myThread1.setPriority(1);
        myThread1.start();
        System.out.println(myThread.getState());
    }
}
public class MyThread extends Thread {
    @Override
    public void run() {
       for(int i = 0;i<1000;i++){
           System.out.println(Thread.currentThread().getId());//线程Id
           System.out.println(Thread.currentThread().getName());
           System.out.println(Thread.currentThread().getPriority());
           System.out.println(Thread.currentThread().getState());
       }
    }
}

public class MyThread extends Thread {
    @Override
    public void run() {
        /*try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }*/
        for(int i = 0;i<1000;i++){
            Thread thread = Thread.currentThread();
            if(i%10==0){
                Thread.yield();//主动礼让 退出cpu
            }
            System.out.println(thread.getName()+":"+i);
        }
    }
}
public class ThreadTest {
    public static void main(String[] args) {
        MyThread myThread = new MyThread();
        myThread.setName("窗口1");
        myThread.start();
        MyThread myThread1 = new MyThread();
        myThread1.setName("窗口2");
        myThread1.start();
    }
}

创建线程的方式


public class ThreadTest {
    public static void main(String[] args) {
        //创建并启动线程
        MyThread myThread = new MyThread();
        //myThread.run();这不是启动线程,只是一个方法调用,没有启动线程,还是单线程模式
        myThread.start();

        for (int i = 0;i<1000;i++){
            System.out.println("main:"+i);
        }
    }
}
public class ThreadTest2 {
    public static void main(String[] args) {
        //创建任务
        Task task = new Task();
        //创建线程,并为线程指定执行任务
        Thread thread = new Thread(task);
        thread.start();

        for (int i = 0;i<1000;i++){
            System.out.println("main:"+i);
        }
    }
}
public class Task implements Runnable {
    @Override
    public void run() {
        for (int i = 0;i<1000;i++){
            System.out.println("自定义线程:"+i);
    }
    /*
    java中创建线程方式2:
       只先创建线程要执行的任务,创建一个类,实现Runnable接口
       重写任务执行的run()

       实现Runnable接口创建的优点:
         1.因为java是单继承,一旦继承一个类就不能再继承其他类,避免单继承的局限
         2.适合多线程来处理同一资源时使用
     */

    }
}


抢票系统


public class TicketThread extends Thread {
    static int num = 10;
    static Object object = new Object();
    /*
    synchronized (同步锁对象){
       同步代码块
    }
    同步锁对象作用:
               用来记录有没有线程进入到同步代码块中,如果有线程进入到同步代码块,那么其他线程就不能进
               直到上一个钱程技行完同步代码块的内容,释旅锁之后,其他钱程才能进入
    同步锁对象要求:
               阃步锁对象必须是唯一的(多个线程拿到的是间一个对象)
     */

    /*@Override
    public void run() {
        while (true) {
            synchronized (object) {
                if (num > 0) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(Thread.currentThread().getName() + "买到第" + num + "张票");
                    num--;
                } else {
                    break;
                }
            }
        }
    }*/
/* synchronized修饰方法时,同步锁对象不需要我们指定
    同步锁对象会默认提供:1.非静念的方法--锁对象默认是this
    2.静态方法--锁对象是当前类的class对象
    */
    @Override
    public void run() {
        while (true){
            if(num<=0){
                break;
            }
            print();
        }
    }
    public static synchronized void print(){
        if(num>0){
            System.out.println(Thread.currentThread().getName()+"买到了第"+num+"张票");
            num--;
        }
    }
}
public class TicketTest {
    public static void main(String[] args) {
        TicketThread t1 = new TicketThread();
        t1.setName("窗口1");
        t1.start();

        TicketThread t2 = new TicketThread();
        t2.setName("窗口2");
        t2.start();
    }
}


同步锁


public class PrintNumThread extends Thread {
    static int num = 1;
    static String obj = new String();//同步锁
    @Override
    public void run() {
        while (num<100){
            synchronized (obj){
                obj.notify();//唤醒等待的线程
                System.out.println(Thread.currentThread().getName()+":"+num);
                num++;
                try {
                    obj.wait();//让线程等待,会自动的释放锁,notify(),wait()必须在同步代码块中使用,必须是通过锁对象调用的
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
public class ThreadTest {
    public static void main(String[] args) {
        PrintNumThread printNumThread = new PrintNumThread();
        printNumThread.setName("线程1");
        printNumThread.start();
        PrintNumThread printNumThread1 = new PrintNumThread();
        printNumThread1.setName("线程2");
        printNumThread1.start();
    }
}

生产者/消费者问题
在这里插入图片描述

public class Counter {
    int num = 0;//柜台可以存放的商品数量

    //生产者线程调用 添加商品
    public synchronized void add() throws InterruptedException {//锁对象是this,两个方法共有一个锁
        if(num==0){
            this.notify();//唤醒消费者
            num = 1;
            System.out.println("生产者线程生产了一件商品");
        }else {//商品不为空,进入等待
            this.wait();
        }
    }
    public synchronized void sub() throws InterruptedException {
        if(num>0){
            this.notify();
            num = 0;
            System.out.println("消费者取走了一件商品");
        }else {
            this.wait();//没有商品,进入等待·
        }
    }
}

public class CustomerThread extends Thread {
    /*
    消费者线程
     */
    Counter counter;
    public CustomerThread(Counter counter){
        this.counter = counter;
    }

    @Override
    public void run() {
        while (true){//消费者线程一直消费
            try {
                this.counter.sub();
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
/*
生产者线程
 */
public class ProductorThread extends Thread {
    Counter counter;
    public ProductorThread (Counter counter){
        this.counter = counter;
    }

    @Override
    public void run() {
        while (true){//生产者线程一直生产
            try {
                this.counter.add();
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
public class Test {
    public static void main(String[] args) {
        Counter counter = new Counter();//只创建一个柜台对象

        ProductorThread productorThread = new ProductorThread(counter);
        productorThread.setName("生产者线程");

        CustomerThread customerThread = new CustomerThread(counter);
        customerThread.setName("消费者线程");

        productorThread.start();
        customerThread.start();
    }
}


Callable


import java.util.concurrent.Callable;

public class SumTask<T> implements Callable<T> {

    @Override
    public T call() throws Exception {
        Integer n = 0;
        for(int i = 0;i<10;i++){
            n+=i;
        }
        return (T)n;
    }
}
import java.util.concurrent.Callable;

public class SumTask<T> implements Callable<T> {

    @Override
    public T call() throws Exception {
        Integer n = 0;
        for(int i = 0;i<10;i++){
            n+=i;
        }
        return (T)n;
    }
}
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值