让出CPU
package cn.cast;
@SuppressWarnings({ "rawtypes", "unchecked" })
public class HelloWorld {
public static void main(String[] args) {
new MyThread().start();
new MyThread().start();
}
}
class MyThread extends Thread {
public void run() {
for(int i = 1; i <= 1000; i++) {
if(i % 20 == 0) {
Thread.yield();
}
System.out.println(getName() + "...." + i);
}
}
}
优先级
package cn.itcast.thread;
public class Demo2_Priority {
/**
* @param args
* setPriority()设置线程优先级
* 最高级别是10Thread.MAX_PRIORITY
* 最低级别是1Thread.MIN_PRIORITY
*/
public static void main(String[] args) {
Thread t1 = new Thread() {
public void run() {
for(int i = 0; i < 1000; i++) {
System.out.println(getName() + "...aaaaaaaaaaaaa");
}
}
};
Thread t2 = new Thread() {
public void run() {
for(int i = 0; i < 1000; i++) {
System.out.println(getName() + "...bb");
}
}
};
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
}
}
设置关机
package cn.itcast.thread;
import java.io.IOException;
public class Demo4_Runtime {
/**
* @param args
* @throws IOException
*/
public static void main(String[] args) throws IOException {
Runtime r = Runtime.getRuntime();
r.exec("shutdown -a");
}
}
定时器
package cn.cast;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
@SuppressWarnings({ "rawtypes", "unchecked" })
public class HelloWorld {
/**
* @param args
* Timer是一个计时器类,在指定时间执行指定任务
* @throws InterruptedException
*/
@SuppressWarnings("deprecation")
public static void main(String[] args) throws InterruptedException {
Timer t = new Timer();
t.schedule(new MyTimerTask(), new Date(118, 6, 8, 16, 30 , 30));
t.schedule(new MyTimerTask(),3000);
t.schedule(new MyTimerTask(), new Date(118, 6, 8, 16, 33 , 00),3000);
while(true) {
Thread.sleep(1000);
System.out.println(new Date());
}
}
}
class MyTimerTask extends TimerTask {
@Override
public void run() {
System.out.println("起床背英语单词");
}
}
条件锁
package cn.itcast.thread;
public class Demo06_Notify {
/**
* @param args
*/
public static void main(String[] args) {
final Printer p = new Printer();
new Thread() {
public void run() {
while(true) {
try {
p.print1();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
new Thread() {
public void run() {
while(true) {
try {
p.print2();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
new Thread() {
public void run() {
while(true) {
try {
p.print3();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
}
class Printer {
private int flag = 1;
private Object obj = new Object();
public void print1() throws InterruptedException {
synchronized(this) {
while(flag != 1) {
this.wait();
}
System.out.print("1");
System.out.print("2");
System.out.print("3");
System.out.print("4");
System.out.print("5");
System.out.print("\r\n");
flag = 2;
this.notifyAll();
}
}
public void print2() throws InterruptedException {
synchronized(this) {
while(flag != 2) {
this.wait();
}
System.out.print("a");
System.out.print("b");
System.out.print("c");
System.out.print("d");
System.out.print("\r\n");
flag = 3;
this.notifyAll();
}
}
public void print3() throws InterruptedException {
synchronized(this) {
while(flag != 3) {
this.wait();
}
System.out.print("i");
System.out.print("t");
System.out.print("c");
System.out.print("a");
System.out.print("s");
System.out.print("t");
System.out.print("\r\n");
flag = 1;
this.notifyAll();
}
}
}
互斥锁
package cn.itcast.thread;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class Demo07_ReentrantLock {
/**
* 1.5版本的新特性互斥锁
* 1.同步
* 使用ReentrantLock类的lock()和unlock()方法进行同步
* 2.通信
* 使用ReentrantLock类的newCondition()方法可以获取Condition对象
* 需要等待的时候使用Condition的await()方法, 唤醒的时候用signal()方法
* 不同的线程使用不同的Condition, 这样就能区分唤醒的时候找哪个线程了
*/
public static void main(String[] args) {
final Printer2 p = new Printer2();
new Thread() {
public void run() {
while(true) {
try {
p.print1();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
new Thread() {
public void run() {
while(true) {
try {
p.print2();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
new Thread() {
public void run() {
while(true) {
try {
p.print3();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
}
class Printer2 {
private ReentrantLock r = new ReentrantLock();
private Condition c1 = r.newCondition();
private Condition c2 = r.newCondition();
private Condition c3 = r.newCondition();
private int flag = 1;
public void print1() throws InterruptedException {
r.lock();
if(flag != 1) {
c1.await();
}
System.out.print("1");
System.out.print("2");
System.out.print("3");
System.out.print("4");
System.out.print("5");
System.out.print("\r\n");
flag = 2;
c2.signal();
r.unlock();
}
public void print2() throws InterruptedException {
r.lock();
if(flag != 2) {
c2.await();
}
System.out.print("1");
System.out.print("2");
System.out.print("3");
System.out.print("4");
System.out.print("\r\n");
flag = 3;
c3.signal();
r.unlock();
}
public void print3() throws InterruptedException {
r.lock();
if(flag != 3) {
c3.await();
}
System.out.print("i");
System.out.print("t");
System.out.print("c");
System.out.print("a");
System.out.print("s");
System.out.print("t");
System.out.print("\r\n");
flag = 1;
c1.signal();
r.unlock();
}
}
线程组
package cn.itcast.thread;
public class Demo08_ThreadGroup {
/**
* @param args
* public final ThreadGroup getThreadGroup()//通过线程对象获取他所属于的组
* public final String getName()//通过线程组对象获取他组的名字
*
* 默认是主线程组
*/
public static void main(String[] args) {
ThreadGroup tg = new ThreadGroup("我是一个线程组");
Thread t1 = new Thread(tg, new MyRunnable(), "张三");
Thread t2 = new Thread(tg, new MyRunnable(), "李四");
System.out.println(tg.getName());
}
public static void demo1() {
MyRunnable mr = new MyRunnable();
Thread t1 = new Thread(mr, "张三");
Thread t2 = new Thread(mr, "李四");
ThreadGroup tg1 = t1.getThreadGroup();
ThreadGroup tg2 = t2.getThreadGroup();
System.out.println(tg1.getName());
System.out.println(tg2.getName());
}
}
线程池
package cn.itcast.thread;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Demo09_Executors {
/**
* JDK5新增了一个Executors工厂类来产生线程池,有如下几个方法
* public static ExecutorService newFixedThreadPool(int nThreads)
* public static ExecutorService newSingleThreadExecutor()
* 这些方法的返回值是ExecutorService对象,该对象表示一个线程池,可以执行Runnable对象或者Callable对象代表的线程。它提供了如下方法
* Future<?> submit(Runnable task)
* <T> Future<T> submit(Callable<T> task)
* 使用步骤:
* 创建线程池对象
* 创建Runnable实例
* 提交Runnable实例
* 关闭线程池
*/
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
MyRunnable mr1 = new MyRunnable();
MyRunnable mr2 = new MyRunnable();
pool.submit(mr1);
pool.submit(mr2);
pool.shutdown();
}
}
Callable的使用
package cn.itcast.thread;
import java.util.concurrent.Callable;
public class MyCallable implements Callable<Integer> {
private int num;
public MyCallable(int num) {
this.num = num;
}
@Override
public Integer call() throws Exception {
int sum = 0;
for(int i = 1; i <= num; i++) {
sum = sum + i;
}
return sum;
}
}
package cn.itcast.thread;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Demo10_Callable {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService pool = Executors.newFixedThreadPool(2);
MyCallable mc1 = new MyCallable(100);
MyCallable mc2 = new MyCallable(200);
Future<Integer> f1 = pool.submit(mc1);
Future<Integer> f2 = pool.submit(mc2);
Integer i1 = f1.get();
Integer i2 = f2.get();
System.out.println(i1);
System.out.println(i2);
pool.shutdown();
}
}