1.继承Thread类
继承Thread类并重写run()方法
调用当前类对象的start()方法会自动启动线程并线程调用run方法。
public class Thread3 extends Thread{ @Override public void run() { super.run(); } }
public void test3() throws InterruptedException { Thread t3 = new Thread3(); t3.start(); }
2.实现runnable接口
与继承Thread类相似,实现run()方法。
public class Thread2 implements Runnable { public Thread2(){ System.out.println("thread2 is creating......"); } public void run() { System.out.println("hahaha"); } }
Thread t1 = new Thread(new Thread2(),"thread1");//参数1:开启的对象 参数2:线程的name
3.实现callable接口,带返回值类型为Callable<Object>
实现Callable接口的call()方法
将这个Callable接口实现类的对象作为参数传递到FutureTask类的构造器中,创建FutureTask类的对象。
将这个FutureTask类的对象作为参数传递到Thread类的构造器中,创建Thread类的对象,并调用这个对象的start()方法。
public class Thread5 implements Callable<String> { public Object call() throws Exception { System.out.println("hahahaha"); return "实现Callable接口的线程...."; } }
public void test4() throws InterruptedException { Thread5 thread5 = new Thread5(); FutureTask futureTask = new FutureTask(thread5); Thread thread = new Thread(futureTask,"thread"); thread.start(); }
4.线程池启动
创建线程池,定义线程池线程数量,执行完关闭线程池
ExecutorService service = Executors.newFixedThreadPool(1);
Runnable线程
service.execute(runnable);
service.shutdown();
Callable线程
Future<Boolean> r1 = service.submit(t1);
service.shutdown()
5.线程阻塞
sleep(int)线程阻塞,时间单位毫秒
锁(synchronized、ReentrantLock)
synchronized:方法锁和代码块锁
synchronized(上锁对象){ 代码块... }
private synchronized void mothed(){}
ReentrantLock:代码块锁
try{ lock.lock() 代码块 }finally{ lock.unlock() }
6.线程等待
wait()放弃对象锁进行等待,其它线程可以获取该对象锁
notifyAll()//唤醒获取对象锁的所有线程,cpu随机分配对象锁给线程
浙公网安备 33010602011771号