1.程序、进程、线程:
2.创建线程
class MyThread1 extends Thread{
@Override
public void run() {
for (int i = 0; i < 100; i++) {
try {
//让当前线程休眠10毫秒
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(i+"====="+Thread.currentThread().getName());
}
}
}
public class ThreadTest {
public static void main(String[] args){
//主方法线程循环打印0-499
for (int i = 0; i < 500; i++) System.out.println(i+"====="+Thread.currentThread().getName());
//创建自定义线程对象
MyThread thread = new MyThread();
//重新命名自定义线程
thread.setName("MyThread");
//设置线程优先级
thread.setPriority(Thread.MAX_PRIORITY);
//启动自定义线程
thread.start();
}
class MyRunnable implements Runnable{
@Override
public void run() {
for (int i = 0; i < 100; i++) System.out.println(i+"====="+Thread.currentThread().getName())
}
}
public class ThreadTest {
public static void main(String[] args){
for (int i = 0; i < 500; i++) System.out.println(i+"====="+Thread.currentThread().getName());
Thread thread1=new Thread(new MyRunnable(),"MyRunnable");
thread1.setPriority(Thread.MAX_PRIORITY);
thread1.start();
}
}
class MyCallable implements Callable{
@Override
public Integer call() throws Exception { //返回类型为Integer
Thread.sleep(100);
int sum = 0;
for(int i=0;i<100;i++) sum += i;
return sum;
}
}
public class FutureTest {
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool(); //构造线程池
MyCallable task = new MyCallable();
Future result = executor.submit(task); //获取任务执行结果
executor.shutdown();
try {
System.out.println("task运行结果"+result.get());
} catch (Exception e) {
e.printStackTrace();
}
}
}
3.线程的状态:
4.线程的同步机制
方式一:同步代码块:
synchronized( 同步监视器 ){ //操作共享数据的代码 }
方式二:同步方法:
将操作共享数据的方法声明为synchronized。
比如:public synchronized void show(){ //操作共享数据的代码}
注:①.对于非静态的方法而言,使用同步的话,默认锁为:this。如果使用在继承的方式实现多线程 的话,慎用this!
②静态的方法如果使用同步,默认的锁为:当前类本身。
tips:
public class DeadLock {
private static String Stephen="Stephen";
private static String Curry="Curry";
public static void main(String[] args){
new DeadLock().deadLock();
}
private void deadLock(){
Thread threadA=new Thread(new Runnable(){
@Override
public void run(){
synchronized(Stephen){
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(Curry){
System.out.println("AB");
}
}
}
}).start();
Thread threadB=new Thread(new Runnable(){
@Override
public void run(){
synchronized(Curry){
try {
Thread.currentThread().sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
synchronized(Stephen){
System.out.println("BA");
}
}
}
}).start();
}
}
5.线程的通信
①两个线程交替打印1-100自然数
public class CommunicationTest {
public static void main(String[] args) {
Print print = new Print();
Thread thread1 = new Thread(print);
Thread thread2 = new Thread(print);
thread1.setName("线程1打印:");
thread1.start();
thread2.setName("线程2打印:");
thread2.start();
}
}
class Print implements Runnable {
public static int num = 1;
@Override
public void run() {
while (true) {
synchronized (this) {
if (num <= 100) {
//唤醒另外一个线程
this.notify();
System.out.println(Thread.currentThread().getName()+(num++));
try {
wait(); //该线程释放资源进去阻塞状态
} catch (InterruptedException e) {
e.printStackTrace();
}
} else break;
}
}
}
}
②生产者与消费者
public class TestProductAndCustomer {
public static void main(String[] args) {
Waitter waitter = new Waitter();
Productor p = new Productor(waitter);
Customer c1 = new Customer(waitter);
Customer c2 = new Customer(waitter);
new Thread(p).start();
new Thread(c1).start();
new Thread(c2).start();
}
}
class Waitter {
private int produce = 0;
public synchronized void produce() {
if (produce < 20) {
produce++;
System.out.println(Thread.currentThread().getName() +
"生产了第" + produce + "个产品");
notify();
} else {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public synchronized void custom() {
if (produce > 0) {
System.out.println(Thread.currentThread().getName() +
"消费了第" + produce + "个产品");
produce--;
notify();
} else {
try {
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class Productor implements Runnable {
private Waitter waitter;
public Productor(Waitter waitter) {
this.waitter = waitter;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
waitter.produce();
}
}
}
class Customer implements Runnable {
private Waitter waitter;
public Customer(Waitter waitter) {
this.waitter = waitter;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(20);
} catch (InterruptedException e) {
e.printStackTrace();
}
waitter.custom();
}
}
}
tips:
线程的通信:如下的三个方法必须使用在同步代码块或同步方法中:
wait():当在同步中,执行到此方法,则此线程“等待”,直至其他线程执行notify()的方法,将其唤醒,唤醒后继续其wait()后的代码
notify()/notifyAll():在同步中,执行到此方法,则唤醒其他的某一个或所有的被wait的线程。
线程安全的懒汉式:
class SingleTon{
private static SingleTon instance;
private SingleTon() {}
public static SingleTon1 getIntance(){
if (instance==null){
synchronized (SingleTon1.class){
if(instance==null)
return instance=new SingleTon1();
}
}
return instance;
}
}