java多线程

import org.codehaus.groovy.control.ProcessingUnit;

import java.util.Map;

/**
 * @description:
 * @author: ljx
 * @time: 2020/7/13 10:25
 */
public class ThreadDemo {
    public static void main(String[] args) throws InterruptedException {
//        testDemon();
        test_synchronized();
    }

    public void testThread() throws InterruptedException {
        MyThread t1 = new MyThread();
        Mythread2 t2 = new Mythread2();

        System.out.println(Thread.currentThread().getName() + "==run....");
        //第三种方法,可以避免写类
        Thread t3 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int a = 0; a < 10; a++) {
                    System.out.println(Thread.currentThread().getName() + "---run....");
                }
            }
        }, "c");
        t1.start();
        new Thread(t2, "A").start();
        t3.start();
        //join() 方法让一个线程强制运行,线程强制运行期间,其他线程无法运行,必须等待此线程完成之后才可以继续执行
        t1.join();
        t1.interrupt();//终止线程
    }

    public static void testDemon() {
        // run() 方法中是死循环的方式,但是程序依然可以执行完,因为方法中死循环的线程操作已经设置成后台运行
        MyThread1 t1 = new MyThread1();
        Thread t = new Thread(t1);
        t.setDaemon(true);
        t.start();
    }

    public static void test_synchronized() {
        MyThread4 mt = new MyThread4();  // 定义线程对象
        Thread t1 = new Thread(mt);    // 定义Thread对象
        Thread t2 = new Thread(mt);    // 定义Thread对象
        Thread t3 = new Thread(mt);    // 定义Thread对象
        t1.start();
        t2.start();
        t3.start();
    }
}

//继承Thread类
class MyThread extends Thread {
    @Override
    public void run() {
        for (int a = 0; a < 10; a++) {
            System.out.println(Thread.currentThread().getName() + "---run....");
            try {
                Thread.sleep(1000);//即可实现休眠
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

//实现Runnable接口
class Mythread2 implements Runnable {
    @Override
    public void run() {
        for (int a = 0; a < 10; a++) {
            System.out.println(Thread.currentThread().getName() + "---run....");
        }
    }
}

class MyThread1 implements Runnable { // 实现Runnable接口
    public void run() {  // 覆写run()方法
        while (true) {
            System.out.println(Thread.currentThread().getName() + "在运行。");
        }
    }
};

class MyThread4 implements Runnable {
    private int ticket = 5;    // 假设一共有5张票

    public void run() {
        for (int i = 0; i < 100; i++) {
            synchronized (this) { // 要对当前对象进行同步
                if (ticket > 0) {   // 还有票
                    try {
                        Thread.sleep(300); // 加入延迟
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println("卖票:ticket = " + ticket--);
                }
            }
        }
    }
}


 

你可能感兴趣的:(java基础)