欢迎访问宙启技术站
智能推送

在Java中使用多线程的示例代码

发布时间:2023-06-13 16:29:33

Java是一种支持多线程编程的面向对象编程语言。多线程是一种并发编程技术,在一个程序中同时运行多个线程,利用CPU的多核心特性,来提高程序的执行效率。

以下是Java中使用多线程的示例代码:

1. 继承Thread类

public class MyThread extends Thread {
    public void run() {
        System.out.println("MyThread is running.");
    }
}

public class MultiThreadDemo {
    public static void main(String[] args) {
        MyThread t = new MyThread();
        t.start();
    }
}

2. 实现Runnable接口

public class MyRunnable implements Runnable {
    public void run() {
        System.out.println("MyRunnable is running.");
    }
}

public class MultiThreadDemo {
    public static void main(String[] args) {
        MyRunnable r = new MyRunnable();
        Thread t = new Thread(r);
        t.start();
    }
}

3. 使用匿名内部类创建线程

public class MultiThreadDemo {
    public static void main(String[] args) {
        Thread t = new Thread(new Runnable() {
            public void run() {
                System.out.println("Thread is running.");
            }
        });
        t.start();
    }
}

4. 使用Lambda表达式创建线程

public class MultiThreadDemo {
    public static void main(String[] args) {
        Thread t = new Thread(() -> {System.out.println("Thread is running.");});
        t.start();
    }
}

5. 线程同步

public class SynchronizedDemo {
    public static void main(String[] args) {
        MyRunnable r = new MyRunnable();
        Thread t1 = new Thread(r);
        Thread t2 = new Thread(r);
        t1.start();
        t2.start();
    }
}

public class MyRunnable implements Runnable {
    private static int count = 0;
    public void run() {
        synchronized (this) {
            for(int i = 0; i < 5; i++) {
                count++;
                System.out.println(Thread.currentThread().getName() + ": " + count);
                try {
                    Thread.sleep(100);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

以上是Java中使用多线程的示例代码,需要注意的是,在多线程编程中,要考虑线程安全的问题,避免资源竞争导致的数据不一致问题。