多线程

来源:互联网 发布:知柏地黄丸能壮阳吗 编辑:程序博客网 时间:2024/05/20 17:08
package com.text;/** * 多线程 */public class ManyThread {public static void main(String[] args) {// ex();// im();// im1();// inner();}/** * 匿名内部类实现线程 */private static void inner() {// 继承Thread类new Thread() {@Overridepublic void run() {System.out.println("****************");}}.start();// 实现Runnable接口new Thread(new Runnable() {public void run() {System.out.println("****************");}}).start();}public static void ex() {new ExThread("exThread1").start();// 启动线程new ExThread("exThread2").start();}public static void im() {ImRunnable im = new ImRunnable();Thread im1 = new Thread(im, "im1");Thread im2 = new Thread(im, "im2");// 启动线程im1.start();im2.start();}public static void im1() {ImRunnable1 im = new ImRunnable1();Thread im3 = new Thread(im, "im3");Thread im4 = new Thread(im, "im4");im3.start();im4.start();}}/** *  * 继承Thread类实现线程 *  */class ExThread extends Thread {private static int count = 10;public ExThread(String name) {super(name);}@Overridepublic void run() {while (count > 0) {try {// 使线程沉睡100毫秒Thread.sleep(100);} catch (InterruptedException e) {e.printStackTrace();}count--;System.out.println(Thread.currentThread().getName()+ " : count is " + count);}}}/** * 实现Runnable接口实现线程 (可以实现资源的共享,是Thread类的拓展,较实现Thread类更加的灵活,推荐使用此种方式实现线程) * <p> *  * 同步的实现方式(同步是在一个时间里,只允许一个线程执行,其他线程在执行线程结束后,才能逐个执行) * <p> * 1)同步代码块 * <p> * 2)同步方法 */class ImRunnable implements Runnable {private int count = 10;public void run() {while (count > 0) {// 同步代码块synchronized (ImRunnable.this) {if (count > 0) {try {Thread.sleep(10);} catch (InterruptedException e) {e.printStackTrace();}if (count == 0) {System.out.println("error");}System.out.println(Thread.currentThread().getName()+ " : count is " + count--);}}}}}class ImRunnable1 implements Runnable {private int count = 10;public void run() {while (count > 0) {count();}}// 同步方法public synchronized void count() {if (count > 0) {try {Thread.sleep(1000);} catch (InterruptedException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println(Thread.currentThread().getName()+ " : count is " + count--);}}}

0 0