I run the following code, when I use jstack check thread information, found 100 threads in the runnable state. I know what is the maximum number of CPU thread of execution core * 2, but I'm very confused, even jstack is not instantaneous, why is a runnable thread?Or is not executed by the CPU thread state is runnable.
Has not been thread of execution, his status is also a runnable?
public static void main(String[] args) {
for (int i = 0; i < 100; i++) {
new Thread(() -> {
long last = System.currentTimeMillis();
try {
byte[] buf = new byte[1024];
FileInputStream fileInputStream = new FileInputStream("");
while (fileInputStream.read(buf) != -1) {
}
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("read over " + (System.currentTimeMillis() - last) );
}, "name" + i).start();
}
}
Related
public class MainLock {
public static void main(String[] args) throws Exception {
LockClass lock = new LockClass();
Thread t1 = new Thread(new Runnable() {
#Override
public void run() {
lock.incrementa();
}
});
Thread t2 = new Thread(new Runnable() {
#Override
public void run() {
lock.incrementb();
}
});
Thread t3 = new Thread(new Runnable() {
#Override
public void run() {
lock.incrementa();
}
});
t1.start();
t2.start();
t3.start();
}
}
public class LockClass {
int a;
int b;
ReentrantLock lock = new ReentrantLock();
public void incrementa() {
lock.lock();
try {
for (int i = 0; i < 3; i++) {
System.out.println("a " + a++);
Thread.sleep(1000);
}
lock.unlock();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public void incrementb() {
try {
lock.lock();
for (int i = 0; i < 3; i++) {
System.out.println("b " + b++);
Thread.sleep(1000);
}
lock.unlock();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
The output above result is
a0 a1 a2 b0 b1 b2 a3 a4 a5
I want to achieve a0 b0 a1 b1 a2 b2 a3 a4 a5, thread t1 and t2 should run parallely and t3 should be blocked because of lock by t1.
I know using static synchronization in incrementb() will work but I am looking something only with locks.
I am looking for Method level locking, not object level or class level
I there any way in java to achieve this.
I am looking something only with locks
That's not what locks are for. Pretty much the only thing you should use locks* for is to ensure safe access to shared variables. You should not try to use locks for signaling between threads.
I want to achieve a0 b0 a1 b1 a2 b2...
The best way to make certain things happen in a certain order is to do all of those things in the same thread. You can make threads take turns like that, but it completely defeats the purpose of using threads. The purpose of using threads is to allow different parts of a program to run concurrently, and that is exactly what you are not allowing the threads to do when you force them to take turns.
If you really want to make the threads take turns (e.g., if this is a homework assignment**) then IMO the best way to do that is to pass a virtual token from thread to thread. Holding the token means, "it's your turn."
One way to do it is to use Semaphore objects: Make one semaphore per thread, but give each thread a reference to two of them. Each thread will use one semaphore to receive the token, and the other semaphore to pass the token off to the next thread:
class MyRunnable {
private Semaphore token_in;
private Semaphore token_out;
public MyRunnable(Semaphore token_in, Semaphore token_out) {
this.token_in = token_in;
this.token_out = token_out;
}
public void Run() {
while (...thread should keep running...) {
token_in.acquire(); // wait to receive the token.
...do stuff...
token_out.release(); // hand the token to the next thread.
}
}
}
When you start this up, you must make sure that each thread's token_out is the next thread's token_in:
static void main(...) {
int TOKEN = 1;
int EMPTY = 0;
Semaphore s1 = new Semaphore(TOKEN);
Semaphore s2 = new Semaphore(EMPTY);
Semaphore s3 = new Semaphore(EMPTY);
MyRunnable r1 = new MyRunnable(s1, s2);
MyRunnable r2 = new MyRunnable(s2, s3);
MyRunnable r3 = new MyRunnable(s3, s1);
...create and start the three threads for r1, r2, and r3...
}
* "Locks" includes any use of a synchronized block or a synchronized method or a ReentrantLock.
** If you want to tell your instructor what I said about making threads take turns, that's up to you. You'd be doing the world a favor if you can help eradicate this assignment, but only you can decide whether it's politically smart to talk to your instructor about ideas that are above the level of what they're teaching.
Volatile provides reading and writing to program memory bypassing cache. We should use volatile when there is a common resource, such as an integer variable
So, I did a little experiment.
First I had the following classes:
public class Main3 {
static int j = 0;
public static void main(String[] args) throws InterruptedException {
new Thread1().start();
new Thread2().start();
}
static int i = 0;
static class Thread1 extends Thread{
#Override
public void run() {
while(i<5){
System.out.println("thread1 i = "+i);
i++;
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
static class Thread2 extends Thread{
#Override
public void run() {
int val = i;
while(val<5){
if(val!=i) {
System.out.println("thread2 i = " + i);
val = i;
}
}
}
}
}
In the first thread, the variable changes its value. The second thread monitors the change and displays the text on the console if it happened
i variable is a shared resource. And without volatile the program prints what was expected and cant :
thread1 i = 0
thread1 i = 1
thread1 i = 2
thread1 i = 3
thread1 i = 4
But, if i make this (add sleep to Thread2 class):
static class Thread2 extends Thread{
#Override
public void run() {
int val = i;
while(val<5){
if(val!=i) {
System.out.println("thread2 i = " + i);
val = i;
}
try {
sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
the program prints this and successfully finished:
thread1 i = 0
thread2 i = 1
thread1 i = 1
thread2 i = 2
thread1 i = 2
thread2 i = 3
thread1 i = 3
thread2 i = 4
thread1 i = 4
thread2 i = 5
So, if threads cache values, then why does sleep caching disappear with the advent of sleep?
I am trying to make a multiple producer and consumer program. The producers produce random numbers and insert them into a shared queue(shared memory) and the consumers print out the numbers. The user calls the program with the following arguments: number of producer threads, number of consumer threads and the size of the shared data.
Right now it just produces one producer(it seems) and just stops. I wanted to see if I can get some help figuring out how to unlock the consumers.
This is the Queue header
class SyncQueue
{
public:
SyncQueue(int sizeMax);
void enqueue(int value);
int dequeue();
private:
int MaxSize, front, rear, itemcounter;
std::vector<int> QueueElements;
std::mutex mutex;
//Condition variables for full and empty checks
std::condition_variable NotFull;
std::condition_variable NotEmpty;
};
This is the Queue functions
SyncQueue::SyncQueue(int sizeMax)
{
front = 0;
rear = 0;
MaxSize = sizeMax;
itemcounter = 0;
QueueElements.reserve(MaxSize);
}
void SyncQueue::enqueue(int value)
{
std::unique_lock<std::mutex> lock(mutex);
NotFull.wait(lock , [this](){return itemcounter != MaxSize; });
QueueElements[rear] = value;
rear = (rear + 1) % MaxSize;
++itemcounter;
NotEmpty.notify_all();
}
int SyncQueue::dequeue()
{
std::unique_lock<std::mutex> lock(mutex);
NotEmpty.wait(lock, [this](){return itemcounter != 0; });
int number = QueueElements[front];
front = (front + 1) % MaxSize;
--itemcounter;
NotFull.notify_all();
return number;
}
This is main where I create the threads
std::vector<std::thread> producers(producerThreadCount);
std::vector<std::thread> consumers(consumerThreadCount);
SyncQueue queue(size);
//Build producer threads
for (int i = 0; i < producerThreadCount; i++)
{
producers[i] = std::thread(produceThread, i,std::ref(ProducerMutex), std::ref(queue), 200);
}
//Build consumers
for (int i = 0; i < consumerThreadCount; i++)
{
consumers[i] = std::thread(consumeThread, i, std::ref(ConsumerMutex), std::ref(queue), 400);
}
These are the produce and consume threads
void produceThread(int threadId, std::mutex &ProducerMutex, SyncQueue &sharedQueue, int time)
{
while (true)
{
int value = RandomNumberGenerator(std::ref(ProducerMutex));
sharedQueue.enqueue(value);
std::this_thread::sleep_for(std::chrono::milliseconds(time));
}
}
void consumeThread(int threadId, std::mutex &ConsumerMutex, SyncQueue &sharedQueue, int time)
{
while (true)
{
std::lock_guard<std::mutex> lock(ConsumerMutex);
int value;
std::cout << "Thread:" << threadId << " consumes:" <<sharedQueue.dequeue() << std::endl;
std::this_thread::sleep_for(std::chrono::milliseconds(time));
}
}
i am using semaphore for thread communication i have two threads one is OddThread and another is EvenThread ,i am printing value from 1 to 10 OddThread will print only odd numbers between 1 to 10 and EvenThread thread is printing only even numbers between 1 to 10. for that i have used semaphore for threads to communicate properly .what is actually happening is that OddThread is printing only 1 and EvenThread only 2 and then both get stopped. I am not under standing what is actually happening.can any body suggest.
public class ThreadProducerConsumerSemaphore {
/**
* #param args
*/
public static void main(String[] args) {
Semaphore p = new Semaphore(1);
Semaphore c = new Semaphore(0);
OddThread producer = new OddThread(p, c);
EvenThread consumer = new EvenThread(p, c);
Thread t1 = new Thread(producer, "Thread producer");
Thread t2 = new Thread(consumer, "Thread consumer");
t1.start();
t2.start();
}
}
class OddThread implements Runnable {
Semaphore p;
Semaphore c;
public OddThread(Semaphore p, Semaphore c) {
super();
this.p = p;
this.c = c;
}
int counter = 1;
#Override
public void run() {
while (true) {
try {
p.acquire(1);
System.out.println(Thread.currentThread().getName() + " "
+ counter);
if (counter == 10) {
break;
}
counter++;
c.release(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
class EvenThread implements Runnable {
Semaphore p;
Semaphore c;
int counter = 2;
public EvenThread(Semaphore p, Semaphore c) {
super();
this.p = p;
this.c = c;
}
#Override
public void run() {
while (true) {
try {
c.acquire(1);
System.out.println(Thread.currentThread().getName() + " "
+ counter);
if (counter == 10) {
break;
}
counter=counter+2;
p.acquire(1);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Your code can't be correct, it's not even symmetrical.
p.acquire(1);
c.release(1);
c.acquire(1);
p.acquire(1);
Your EvenThread.run method acquires both c and p, rather than releasing one of them.
Note, however, that your code doesn't look like it'll exit properly even once it's been fixed. Consider: neither thread releases a semaphore before it exits, so one of the threads will inevitably be blocked.
here is your problem:
............
c.acquire(1);
System.out.println(Thread.currentThread().getName() + " "
+ counter);
if (counter == 10) {
break;
}
counter=counter+2;
p.acquire(1); <--deadlock this has already been acquired by the other thread.
..............
you should release p here, to allow the other thread to continue; so replace the line I indicated with p.release(1) and it should be fine.
Sample code:
public class ThreadTest{
public static void main(String ...arg){
try{
ExecutorService executor = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
for(int i=0; i < noOfTask; i++){
executor.execute(new ImplRunnable(connectionPool.getConnection()));
}
executor.shutdown();
//Wait for all threads completion
executor.awaitTermination(100, TimeUnit.MICROSECONDS);
}catch(Exception e){
e.printStackTrace();
}finally{
//close database connections etc.
}
}
}
class ImplRunnable implements Runnable{
private Connection conn;
public ImplRunnable(Connection conn){
this.conn = conn;
}
public void run(){
try{
for(int i =0; i < 1000000; i++){
counts++;
}
}catch(Exception exception){
exception.printStackTrace();
}finally{
//close all open statements
try{
conn.close();
}catch(Exception exp){
exp.printStackTrace();
}
}
}
}
My system has 4 cores therefore the pool size is 4 and I have 10 tasks to do
The for loop is opening 10 threads but 4 threads are running at a time. But the problem is when a thread is completed processing it is going in waiting state for forever and not picking up next task for processing. What is wrong with the above code?
Please suggest...
It was my fault only when I was assigning a connection to the thread from Connection Pool then I was not closing it when thread is done with processing. When I closed connection at end of a thread then it started working and threads are properly being assigned for next tasks.