Java高并发代码篇

一、创建线程: 

package com.dong.testThread;
/**
 * 
 * 1.线程的创建
 * 2.线程的方法
 * 
 * @author liuD
 *
 */
public class MultiThread {
	public static void main(String[] args) throws InterruptedException {
		//创建线程1,使用实现Runnable接口的类,使用lambda表达式;
		Thread  trl =new Thread(() -> System.out.println(Thread.currentThread().getName()+ " thread start..."));
		trl.start();
		//使用实现Runnable接口的类,不使用lambda表达式;
		Thread tr = new Thread(new runnableExam());
		tr.start();
		//创建线程2,使用继承了Thread类来创建线程,使用默认的run()
		Thread th = new Thread();
		th.start();
		//创建线程3,使用继承了Thread类的实例做参数。使用重写的run()
		Thread th2 =new Thread(new threadExam());
		
	}
}
class threadExam extends Thread{
	public void run() {
		System.out.println(Thread.currentThread().getName()+ " thread2 start ...");
	}
}
class runnableExam implements Runnable{
	@Override
	public void run() {
		System.out.println(Thread.currentThread().getName()+ " thread start ...");
	}
	
}

二、线程的各个状态:

⑴新建: new()

package com.dong.testThread;
/**
 * 线程的new状态,即刚创建的线程
 * @author liuD
 */
public class TestNew {
	public static void main(String[] args) {
		//使用lambda创建线程;
		Thread t = new Thread(
				() -> System.out.println(Thread.currentThread().getName() + " will running")
				);
	}
}

⑵睡眠:sleep()

package com.dong.testThread;
/**
 * 测试Sleep功能,Sleep是让线程等待million毫秒后在执行
 * @author liuD
 */
public class TestSleep extends Thread{
	StringBuilder str = new StringBuilder();
	public static void main(String[] args) throws InterruptedException {
		Thread thread = new Thread(new TestSleep());
		long startTime  = System.currentTimeMillis();
		//⑵线程睡眠2秒
		thread.sleep(2000);
		long sleepTime  = System.currentTimeMillis();
		//注意这个结果不一定是2000
		System.out.println("thread has sleep "+ (sleepTime - startTime )+ " finish and will start ");
		thread.start();
	}
	public void run(){
		for(int i = 0 ;i< 10;i++) {
			str.append(".");
			System.out.println(str.toString());
		}
	}
}

⑶停止:stop()  (不建议使用)

package com.dong.testThread;
/**
 * 测试stop方法,stop方法会立刻释放锁资源,可能导致数据的不一致;
 * 
 * @author liuD
 *
 */
public class testStop {
	public static void main(String[] args) throws InterruptedException {
		new ReadObjectThread().start();
		while(true) {
			Thread t = new ChangeObjectThread();
			t.start();
			Thread.sleep(100);
			//调用stop()方法;
			t.stop();
		}
	}
}
class User{
	static int a = 0;
	static int b = 0;
	
	public static int getA() {
		return a;
	}
	public static int getB() {
		return b;
	}
	public static void setA() {
		a = a + 1;
	}
	public static void steB() {
		b = b + 1;
	}
}
class  ChangeObjectThread extends Thread{
	public  void run() {
		while(true) {
			synchronized(User.class) {
				User.setA();
				try {
					Thread.sleep(10);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
				User.steB();
			}
			Thread.yield();
		}
	}
}
class ReadObjectThread extends Thread{
	public void run() {
		while(true) {
			synchronized(User.class) {
				if(User.getA() != User.getB()) {
					System.out.println( "A = "+  User.getA() + " B = " + User.getB());
				}
			}
			Thread.yield();
		}
	}
}

⑷中断:interrupte()

package com.dong.testThread;
/**
 * 测试interrupte()方法
 * 当调用interrupte()方法,会给线程发送一个通知,告诉目标线程,该退出,至于如何退出,有目标线程自行决定;
 * interrrupte会通知目标线程中断,也就是设置中断标志位,中断标志位表示当前线程已经被中断了。
 * 刚调用interrupte()方法,相当于只设置了中断标志,但是这个中断不会发生任何作用;
 *如果想显示终止线程,可以使用Thread.currentThread().isInterrupted()方法,判断线程是否已经中断,可以显式中断线程;
 * @author liuD
 *
 */
public class TestInterrupt {
	public static void main(String[] args) throws InterruptedException {
		Thread thread = new Thread(new TThread());
		thread.start();
		thread.sleep(2000);
		//线程的中断不确定,设置了中断标志
		thread.interrupt();
		
		Thread tot = new Thread(new ToThread());
		tot.start();
		//线程的中断不确定,只是设置了中断标志
		tot.interrupt();
	}
}
class TThread implements Runnable{
	@Override
	public void run() {
		while(true) {
			//判断线程是否被中断,显式中断线程的执行;
			if(Thread.currentThread().isInterrupted()) {
				System.out.println(" Interrupted !!! ");
				break;
			}
			System.out.println("TT -----this is thread ...");
		}
		Thread.yield();
	}
}
class ToThread implements Runnable {
	@Override
	public void run() {
		// TODO Auto-generated method stub
		while(true) {
			System.out.println("ToT-----this is thread ...");
		}
	}
	
}

⑸等待:wait()   

⑹唤醒:notify()

package com.dong.testThread;
/**
 * wait()方法和notify()方法是在object类中定义的,
 * wait()让当然线程等待,进入锁对象的等待队列,直到有线程调用notify()方法,才会从等待队列中随机选择一个等待线程进行唤醒,
 * notify()方法从等待队列总随机选择一个线程进行唤醒;
 * @author liuD
 *
 */
public class TestWaitAndNotify {
	final static Object object = new Object();
	public static void main(String[] args) {
		Thread t1  = new Thread(new ToThreads());
		t1.start();
		Thread t2 = new Thread(new ToT2Threads());
		t2.start();
	}

static class ToThreads implements Runnable{
	@Override
	public void run() {
		synchronized (object) {
			System.out.println(System.currentTimeMillis()+ " : T1 start ");
			try {
				System.out.println(System.currentTimeMillis()+": T1 wait for object" );
				object.wait();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			System.out.println(System.currentTimeMillis()+": T1 end !");
		}
	}	
}
static class ToT2Threads implements Runnable{
	public void run() {
		synchronized(object) {
			System.out.println(System.currentTimeMillis()+ " :T2 start notify one thread");
			object.notify();
			System.out.println(System.currentTimeMillis()+ " : T2 end! ");			
			try {
				Thread.sleep(2000);
			}catch(InterruptedException e) {}
		}
	}
	}
}

⑻谦让:yield

package com.dong.testThread;
/**
 * yield()方法会让当前线程让出Cpu的执行权,停止执行,从而重新争取cpu的资源,
 * @author liuD
 */
public class testYield {
	public static void main(String[] args) {
		Thread t1 = new Thread(new T1());
		Thread t2 = new Thread(new T2());
		//多个线程之间的执行是随机的,因此使用yield()方法,看不出来谦让的效果,所以设置一个高优先级和低优先级线程,来观察yield()的效果
		t1.setPriority(10);
		t2.setPriority(1);
		t1.start();
		//可以注释掉t1.yield()语句,来观察输出结果之间的变化;
		t1.yield();
		t2.start();
	}
}
class T1 implements Runnable{
	@Override
	public void run() {
		for(int i = 0;i<20;i++) {
			System.out.println("i \' am a brothers");
		}
	}
}
class T2 implements Runnable{
	@Override
	public void run() {
		// TODO Auto-generated method stub
		for(int j =0;j<20;j++) {
			System.out.println("I \' am a sister");
		}
	}
}

⑼加入:join

package com.dong.testThread;
/**
 * 
 * yield()方法,它会阻塞当前线程,直到目标线程执行完毕,
 * @author liuD
 */
public class TestJoin {
	public static void main(String[] args) throws InterruptedException {
		Thread t1 = new Thread(new joinThread());
		t1.start();
		//阻塞主线程,其他线程愿意等待t1线程执行完毕在执行,这里其他线程指主线程,如果没有t1.join(),则两个线程的输出语句就会随机输出		
		t1.join();
		for(int i = 0 ;i< 1000;i++) {
			System.out.println(Thread.currentThread().getName() +" : " + i);
		}
	}
}
class joinThread implements Runnable{
	public void run() {
		for(int j = 0 ;j < 3;j++) {
		System.out.println(Thread.currentThread().getName()+ " :  start start start " );
		}
	}
}

 

⑽运行:start

就是创建线程后,启动启动线程的方法,threadObject.start()方法;

 

部分代码参考《Java 高并发程序设计》  --葛一鸣,郭超 ,,由衷感谢此书作者为我们提供学习内容

全部评论

相关推荐

10-07 23:57
已编辑
电子科技大学 Java
八街九陌:博士?客户端?开发?啊?
点赞 评论 收藏
分享
10-30 10:16
南京大学 Java
龚至诚:给南大✌️跪了
点赞 评论 收藏
分享
评论
点赞
收藏
分享
牛客网
牛客企业服务