线程

来源:互联网 发布:php mongodb连接池配置 编辑:程序博客网 时间:2024/06/11 22:07
package com.yjcloud.action;//创建一个多线程  继承Thread类/*public class Test extends Thread{public void run(){for(int i=0;i<100;i++) {System.out.println(getName()+" "+i);}System.out.println("创建一个多线程!");}public static void main(String[] args) {Test t = new Test();t.start();Test t2 = new Test();t2.start();}}//创建一个多线程  实现runnable 接口public class Test implements Runnable{@Overridepublic void run() {for (int i=0;i<100;i++) {System.out.println(Thread.currentThread().getName()+" "+i);}}public static void main(String[] args) {Test t = new Test(); new Thread(t,"first").start();; new Thread(t,"second").start();;//也可以//Thread thread1 = new Thread(t);//thread1.start();//Thread thread2 = new Thread(t);//thread2.start();}}*///设置一个线程为后台线程public class Test implements Runnable{@Overridepublic void run() {for (int i=0;i<1000;i++) {System.out.println(Thread.currentThread().getName()+" "+i);}}public static void main(String[] args) throws InterruptedException {Test t = new Test();Thread t1 = new Thread(t,"后台线程!");Thread t2 = new Thread(t,"join线程!");t1.setDaemon(true);  //当主线程结束之后,子线程也随之结束t1.start();//t2.start();//t2.setPriority(10); 设置线程的优先级//Thread.sleep(200);  线程睡眠毫秒(阻塞) 或者用yeled()线程让步 方法System.out.println("线程是否还存活? "+t1.isAlive());for (int i=0;i<10;i++) {//t2.join();  线程的加入。当前线程执行完毕才会执行其他线程System.out.println(Thread.currentThread().getName()+ " "+i);}}/* * 线程安全问题。 * 1,同步代码块: * public void run(){ * synchronized(account){执行体} * } * 2,同步方法: * public synchronized void draw(account){} * 3,同步锁(Lock) * 常用的锁是ReentrantLock(可重入锁) * 用法: *  * class{ * private final ReentrantLock lock = new ReentrantLock(); * //定义需要保证线程安全的方法 *  * public void m(){ * lock.lock(); * try{ * //代码内容 * }finally{ * lock.unclock();  释放锁 * } * } * } *  * 4,死锁 * 两个线程互相等待。 */}

0 0
原创粉丝点击