マルチスレッド(2)ワイヤロック
1:マルチスレッド(理解)
(1)JDK 5以降のスレッドに対するロック操作と解放操作
ロックロック
Demo:
1
2
(2)デッドロック問題の記述とコード表現
Demo:
1
2デッドロック現象
3
(3)生産者と消費者のマルチスレッド表現(スレッド間通信問題)
学生を資源として実現する
リソースクラス:Studio
データクラスの設定:SetThread(生産者)
データ・クラスの取得:GetThread(コンシューマ)
テストクラス:StudentDemo
コード:
A:最も基本的なバージョンは、データが1つしかありません.
Demo:
1
2
3
4
B:バージョンを改善し、異なるデータを提供し、同期メカニズムを追加しました.
Demo:
1
2
3
4
C:起動待ち機構がプログラムを改善し、データが順次出現できるようにする
wait()
notify()
notifyAll()(多生産多消費)
Demo:
1
2
3
4
D:起動メカニズムのコード最適化を待つ.データと操作をリソースクラスに書きました
Demo:
1
2
3
4
(4)スレッドグループ
Demo:
1
(1)JDK 5以降のスレッドに対するロック操作と解放操作
ロックロック
Demo:
1
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class SellTicket implements Runnable {
//
private int tickets = 100;
//
private Lock lock = new ReentrantLock();
@Override
public void run() {
while (true) {
try {
//
lock.lock();
if (tickets > 0) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName()
+ " " + (tickets--) + " ");
}
} finally {
//
lock.unlock();
}
}
}
}
2
/*
* , , ,
* ,JDK5 Lock。
*
* Lock:
* void lock(): 。
* void unlock(): 。
* ReentrantLock Lock .
*/
public class SellTicketDemo {
public static void main(String[] args) {
//
SellTicket st = new SellTicket();
//
Thread t1 = new Thread(st, " 1");
Thread t2 = new Thread(st, " 2");
Thread t3 = new Thread(st, " 3");
//
t1.start();
t2.start();
t3.start();
}
}
(2)デッドロック問題の記述とコード表現
Demo:
1
public class MyLock {
//
public static final Object objA = new Object();
public static final Object objB = new Object();
}
2デッドロック現象
public class DieLock extends Thread {
private boolean flag;
public DieLock(boolean flag) {
this.flag = flag;
}
@Override
public void run() {
if (flag) {
synchronized (MyLock.objA) {
System.out.println("if objA");
synchronized (MyLock.objB) {
System.out.println("if objB");
}
}
} else {
synchronized (MyLock.objB) {
System.out.println("else objB");
synchronized (MyLock.objA) {
System.out.println("else objA");
}
}
}
}
}
3
/*
* :
* A:
* B:
*
* :
* , 。
*
* :
* , 。
* :
* :
* :
* :
* : 1 ,
* : 1 ,
*/
public class DieLockDemo {
public static void main(String[] args) {
DieLock dl1 = new DieLock(true);
DieLock dl2 = new DieLock(false);
dl1.start();
dl2.start();
}
}
(3)生産者と消費者のマルチスレッド表現(スレッド間通信問題)
学生を資源として実現する
リソースクラス:Studio
データクラスの設定:SetThread(生産者)
データ・クラスの取得:GetThread(コンシューマ)
テストクラス:StudentDemo
コード:
A:最も基本的なバージョンは、データが1つしかありません.
Demo:
1
public class Student {
String name;
int age;
}
2
public class SetThread implements Runnable {
private Student s;
public SetThread(Student s) {
this.s = s;
}
@Override
public void run() {
// Student s = new Student();
s.name = " ";
s.age = 27;
}
}
3
public class GetThread implements Runnable {
private Student s;
public GetThread(Student s) {
this.s = s;
}
@Override
public void run() {
// Student s = new Student();
System.out.println(s.name + "---" + s.age);
}
}
4
/*
* :
* :Student
* :SetThread( )
* :GetThread( )
* :StudentDemo
*
* 1: , :null---0
* : ,
* ?
* , 。
*
*/
public class StudentDemo {
public static void main(String[] args) {
//
Student s = new Student();
//
SetThread st = new SetThread(s);
GetThread gt = new GetThread(s);
//
Thread t1 = new Thread(st);
Thread t2 = new Thread(gt);
//
t1.start();
t2.start();
}
}
B:バージョンを改善し、異なるデータを提供し、同期メカニズムを追加しました.
Demo:
1
public class Student {
String name;
int age;
}
2
public class SetThread implements Runnable {
private Student s;
private int x = 0;
public SetThread(Student s) {
this.s = s;
}
@Override
public void run() {
while (true) {
synchronized (s) {
if (x % 2 == 0) {
s.name = " ";// ,
s.age = 27;
} else {
s.name = " "; // ,
s.age = 30;
}
x++;
}
}
}
}
3
public class GetThread implements Runnable {
private Student s;
public GetThread(Student s) {
this.s = s;
}
@Override
public void run() {
while (true) {
synchronized (s) {
System.out.println(s.name + "---" + s.age);
}
}
}
}
4
/*
* :
* :Student
* :SetThread( )
* :GetThread( )
* :StudentDemo
*
* 1: , :null---0
* : ,
* ?
* , 。
*
* 2: , , ,
* A:
* B:
* :
* A:
* CPU , 。
* B:
*
* :
* A:
* B:
* C:
* :
* 。
* :
* A: 。
* B: 。
*/
public class StudentDemo {
public static void main(String[] args) {
//
Student s = new Student();
//
SetThread st = new SetThread(s);
GetThread gt = new GetThread(s);
//
Thread t1 = new Thread(st);
Thread t2 = new Thread(gt);
//
t1.start();
t2.start();
}
}
C:起動待ち機構がプログラムを改善し、データが順次出現できるようにする
wait()
notify()
notifyAll()(多生産多消費)
Demo:
1
public class Student {
String name;
int age;
boolean flag; // , true,
}
2
public class SetThread implements Runnable {
private Student s;
private int x = 0;
public SetThread(Student s) {
this.s = s;
}
@Override
public void run() {
while (true) {
synchronized (s) {
//
if(s.flag){
try {
s.wait(); //t1 ,
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (x % 2 == 0) {
s.name = " ";
s.age = 27;
} else {
s.name = " ";
s.age = 30;
}
x++; //x=1
//
s.flag = true;
//
s.notify(); // t2, , CPU 。
}
//t1 , t2
}
}
}
3
public class GetThread implements Runnable {
private Student s;
public GetThread(Student s) {
this.s = s;
}
@Override
public void run() {
while (true) {
synchronized (s) {
if(!s.flag){
try {
s.wait(); //t2 。 。 ,
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(s.name + "---" + s.age);
// ---27
// ---30
//
s.flag = false;
//
s.notify(); // t1
}
}
}
}
4
/*
* :
* :Student
* :SetThread( )
* :GetThread( )
* :StudentDemo
*
* 1: , :null---0
* : ,
* ?
* , 。
*
* 2: , , ,
* A:
* B:
* :
* A:
* CPU , 。
* B:
*
* :
* A:
* B:
* C:
* :
* 。
* :
* A: 。
* B: 。
*
* 3: , , , 。
* ?
* Java 。
*
* :
* Object :
* wait():
* notify():
* notifyAll():
* Thread ?
* , 。
* , Object 。
*/
public class StudentDemo {
public static void main(String[] args) {
//
Student s = new Student();
//
SetThread st = new SetThread(s);
GetThread gt = new GetThread(s);
//
Thread t1 = new Thread(st);
Thread t2 = new Thread(gt);
//
t1.start();
t2.start();
}
}
D:起動メカニズムのコード最適化を待つ.データと操作をリソースクラスに書きました
Demo:
1
public class Student {
private String name;
private int age;
private boolean flag; // , true,
public synchronized void set(String name, int age) {
// ,
if (this.flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//
this.name = name;
this.age = age;
//
this.flag = true;
this.notify();
}
public synchronized void get() {
// ,
if (!this.flag) {
try {
this.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//
System.out.println(this.name + "---" + this.age);
//
this.flag = false;
this.notify();
}
}
2
public class SetThread implements Runnable {
private Student s;
private int x = 0;
public SetThread(Student s) {
this.s = s;
}
@Override
public void run() {
while (true) {
if (x % 2 == 0) {
s.set(" ", 27);
} else {
s.set(" ", 30);
}
x++;
}
}
}
3
public class GetThread implements Runnable {
private Student s;
public GetThread(Student s) {
this.s = s;
}
@Override
public void run() {
while (true) {
s.get();
}
}
}
4
/*
* :
* :Student
* :SetThread( )
* :GetThread( )
* :StudentDemo
*
* 1: , :null---0
* : ,
* ?
* , 。
*
* 2: , , ,
* A:
* B:
* :
* A:
* CPU , 。
* B:
*
* :
* A:
* B:
* C:
* :
* 。
* :
* A: 。
* B: 。
*
* 3: , , , 。
* ?
* Java 。
*
* :
* Object :
* wait():
* notify():
* notifyAll():
* Thread ?
* , 。
* , Object 。
*
* :
* Student 。
* , 。
* 。
*/
public class StudentDemo {
public static void main(String[] args) {
//
Student s = new Student();
//
SetThread st = new SetThread(s);
GetThread gt = new GetThread(s);
//
Thread t1 = new Thread(st);
Thread t2 = new Thread(gt);
//
t1.start();
t2.start();
}
}
(4)スレッドグループ
Demo:
1
public class MyRunnable implements Runnable {
@Override
public void run() {
for (int x = 0; x
2
/*
* : 。
* ,Java 。
*/
public class ThreadGroupDemo {
public static void main(String[] args) {
// method1();
// ?
//
// ,
method2();
// t1.start();
// t2.start();
}
private static void method2() {
// ThreadGroup(String name)
ThreadGroup tg = new ThreadGroup(" ");
MyRunnable my = new MyRunnable();
// Thread(ThreadGroup group, Runnable target, String name)
Thread t1 = new Thread(tg, my, " ");
Thread t2 = new Thread(tg, my, " ");
System.out.println(t1.getThreadGroup().getName());
System.out.println(t2.getThreadGroup().getName());
// ,
tg.setDaemon(true);
}
private static void method1() {
MyRunnable my = new MyRunnable();
Thread t1 = new Thread(my, " ");
Thread t2 = new Thread(my, " ");
// , ,
// :public final ThreadGroup getThreadGroup()
ThreadGroup tg1 = t1.getThreadGroup();
ThreadGroup tg2 = t2.getThreadGroup();
// :public final String getName()
String name1 = tg1.getName();
String name2 = tg2.getName();
System.out.println(name1);
System.out.println(name2);
// : main
// , , ,
System.out.println(Thread.currentThread().getThreadGroup().getName());
}
}
(5)ラインプール
Demo:
1 public class MyRunnable implements Runnable {
@Override
public void run() {
for (int x = 0; x
2
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/*
* : , , , 。
*
* ?
* A: , 。
* public static ExecutorService newFixedThreadPool(int nThreads)
* B: :
* Runnable Callable
* Runnable 。
* C:
* Future> submit(Runnable task)
* Future submit(Callable task)
* D: , ?
* 。
*/
public class ExecutorsDemo {
public static void main(String[] args) {
// , 。
// public static ExecutorService newFixedThreadPool(int nThreads)
ExecutorService pool = Executors.newFixedThreadPool(2);
// Runnable Callable
pool.submit(new MyRunnable());
pool.submit(new MyRunnable());
//
pool.shutdown();
}
}
(6)マルチスレッド の 3のスキーム
Demo:
1 import java.util.concurrent.Callable;
//Callable: 。
// call() 。
public class MyCallable implements Callable {
@Override
public Object call() throws Exception {
for (int x = 0; x
2
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/*
* 3:
* A: , 。
* public static ExecutorService newFixedThreadPool(int nThreads)
* B: :
* Runnable Callable
* Runnable 。
* C:
* Future> submit(Runnable task)
* Future submit(Callable task)
* D: , ?
* 。
*/
public class CallableDemo {
public static void main(String[] args) {
//
ExecutorService pool = Executors.newFixedThreadPool(2);
// Runnable Callable
pool.submit(new MyCallable());
pool.submit(new MyCallable());
//
pool.shutdown();
}
}
マルチスレッドの :
Demo:
1 import java.util.concurrent.Callable;
/*
*
*/
public class MyCallable implements Callable {
private int number;
public MyCallable(int number) {
this.number = number;
}
@Override
public Integer call() throws Exception {
int sum = 0;
for (int x = 1; x <= number; x++) {
sum += x;
}
return sum;
}
}
2 import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
/*
* 3:
* A: , 。
* public static ExecutorService newFixedThreadPool(int nThreads)
* B: :
* Runnable Callable
* Runnable 。
* C:
* Future> submit(Runnable task)
* Future submit(Callable task)
* D: , ?
* 。
*/
public class CallableDemo {
public static void main(String[] args) throws InterruptedException, ExecutionException {
//
ExecutorService pool = Executors.newFixedThreadPool(2);
// Runnable Callable
Future f1 = pool.submit(new MyCallable(100));
Future f2 = pool.submit(new MyCallable(200));
// V get()
Integer i1 = f1.get();
Integer i2 = f2.get();
System.out.println(i1);
System.out.println(i2);
//
pool.shutdown();
}
}
の クラスによるマルチスレッドの :
Demo: /*
* :
* new () {
* ;
* };
* : 。
*/
public class ThreadDemo {
public static void main(String[] args) {
// Thread
new Thread() {
public void run() {
for (int x = 0; x
:
Demo:
import java.util.Timer;
import java.util.TimerTask;
/*
* : , 。
* Timer TimerTask :
* Timer:
* public Timer()
* public void schedule(TimerTask task,long delay)
* public void schedule(TimerTask task,long delay,long period)
* public void cancel()
* TimerTask:
*/
public class TimerDemo {
public static void main(String[] args) {
//
Timer t = new Timer();
// 3
// t.schedule(new MyTask(), 3000);
//
t.schedule(new MyTask(t), 3000);
}
}
//
class MyTask extends TimerTask {
private Timer t;
public MyTask(){}
public MyTask(Timer t){
this.t = t;
}
@Override
public void run() {
System.out.println("beng, ");
t.cancel();
}
}
Demo2: import java.util.Timer;
import java.util.TimerTask;
/*
* : , 。
* Timer TimerTask :
* Timer:
* public Timer()
* public void schedule(TimerTask task,long delay)
* public void schedule(TimerTask task,long delay,long period)
* public void cancel()
* TimerTask:
*/
public class TimerDemo2 {
public static void main(String[] args) {
//
Timer t = new Timer();
// 3 , , 2
t.schedule(new MyTask2(), 3000, 2000);
}
}
//
class MyTask2 extends TimerTask {
@Override
public void run() {
System.out.println("beng, ");
}
}
Demo3: import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
/*
* : ( c , , demo)
*/
class DeleteFolder extends TimerTask {
@Override
public void run() {
File srcFolder = new File("demo");
deleteFolder(srcFolder);
}
//
public void deleteFolder(File srcFolder) {
File[] fileArray = srcFolder.listFiles();
if (fileArray != null) {
for (File file : fileArray) {
if (file.isDirectory()) {
deleteFolder(file);
} else {
System.out.println(file.getName() + ":" + file.delete());
}
}
System.out.println(srcFolder.getName() + ":" + srcFolder.delete());
}
}
}
public class TimerTest {
public static void main(String[] args) throws ParseException {
Timer t = new Timer();
String s = "2014-11-27 15:45:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date d = sdf.parse(s);
t.schedule(new DeleteFolder(), d);
}
}
(7)マルチスレッドの
1:マルチスレッドにはいくつかの がありますが、それぞれ ですか.
2 です.
Threadクラスの
Runnableインタフェースの
:Callableインタフェースを します.これはスレッドプールと しなければなりません.
2: にはいくつかの があります.それぞれは ですか.
2 です.
コードブロック
メソッド
3:スレッドを するのはrun()ですか、start()ですか. いは?
start();
run():スレッドによって されるコードをカプセル し, び すのは のメソッドの び しにすぎない.
start():スレッドを し、JVMによってrun()メソッドを に び す
4:sleep()とwait()メソッドの い
sleep(): を す があります.ロックを しません.
wait(): を しなくてもいいし、 を してもいいです.ロックを します.
5:なぜwait(),notify(),notifyAll()などのメソッドがObjectクラスに されているのか
これらのメソッドの び しはロックオブジェクトに するため、 コードブロックのロックオブジェクトは のロックである.
Objectコードは のオブジェクトなので、ここで します.
6:スレッドのライフサイクル
-- -- --
→ → →ブロック→ → →
: .